-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestCommonString.java
More file actions
52 lines (41 loc) · 1.06 KB
/
LongestCommonString.java
File metadata and controls
52 lines (41 loc) · 1.06 KB
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
51
52
public class LongestCommonString {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public String longestCommonPrefix(String[] strs) {
if(strs.length <=0 ) return "";
String partialCommon = strs[0];
int commonLength = partialCommon.length();
for(int i = 1; i<strs.length; i++)
{
int index = 0;
while(index < commonLength && index < strs[i].length())
{
if(partialCommon.charAt(index) == strs[i].charAt(index))
{
index ++;
}
else
{
break;
}
}
index = Math.min(index, strs[i].length());
while(index > 0)
{
if(partialCommon.charAt(index - 1) == strs[i].charAt(index-1))
{
break;
}
else{
index --;
}
}
commonLength = index;
}
return partialCommon.substring(0,commonLength);
}
}