-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLongestCommonPrefix.java
50 lines (50 loc) · 1.11 KB
/
LongestCommonPrefix.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
public class LongestCommonPrefix {
public static void main(String[] args) {
String a[] = {"flower","flow","flight"};
System.out.println(longestCommonPrefix(a));
}
public static String longestCommonPrefix(String[] strs) {
int end = -1;
for(int i=0;i>=0;i++)
{
if(isSame(strs, i))
{
end++;
}
else
{
break;
}
}
String ans = "";
for(int i=0;i<=end;i++)
{
ans+=strs[0].charAt(i);
}
return ans;
}
public static boolean isSame(String[] strs, int index)
{
char c = '0';
if(index<strs[0].length())
{
c = strs[0].charAt(index);
}
else
{
return false;
}
for(int i=0;i<strs.length;i++)
{
if(index>=strs[i].length())
{
return false;
}
if(strs[i].charAt(index)!=c)
{
return false;
}
}
return true;
}
}