-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathSolution.java
More file actions
35 lines (32 loc) · 828 Bytes
/
Copy pathSolution.java
File metadata and controls
35 lines (32 loc) · 828 Bytes
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
package LongestCommonPrefix;
/**
* User: Danyang
* Date: 1/17/2015
* Time: 13:00
*
* Write a function to find the longest common prefix string amongst an array of strings.
*/
public class Solution {
/**
* Just iterate
* @param strs
* @return
*/
public String longestCommonPrefix(String[] strs) {
StringBuilder sb = new StringBuilder("");
int i = 0;
if(strs.length==0)
return sb.toString();
while(true) {
if(strs[0].length()-1<i)
return sb.toString();
char c = strs[0].charAt(i);
for(int j=1; j<strs.length; j++) {
if(strs[j].length()-1<i || strs[j].charAt(i)!=c)
return sb.toString();
}
sb.append(c);
i++;
}
}
}