-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path14longest_common_prefix.java
More file actions
38 lines (37 loc) · 1.09 KB
/
14longest_common_prefix.java
File metadata and controls
38 lines (37 loc) · 1.09 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
class Solution {
public String longestCommonPrefix(String[] strs) {
//base case, return directly
if(strs.length == 0){
return "";
}
if(strs.length == 1){
return strs[0];
}
//find the least length, name it min
int min = strs[0].length();
String ans = "";
for(int i=0; i<strs.length; i++){
if(min>strs[i].length()){
min = strs[i].length(); //get the minimum length
}
}
//use nested for loop for comparisons
//use a flag to keep track of the state, if not find, break in advance, else append the character
for(int j=0; j<min; j++){
boolean flag = true;
char c = strs[0].charAt(j);
for (int i=0; i<strs.length; i++){
if(strs[i].charAt(j) != c){
flag = false;
break;
}
}
if(flag){
ans += strs[0].charAt(j);
}else{
break;
}
}
return ans;
}
}