-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathLongestCommonPrefix.java
More file actions
30 lines (25 loc) · 974 Bytes
/
LongestCommonPrefix.java
File metadata and controls
30 lines (25 loc) · 974 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
package LongestCommonPrefix;
public class Solution {
public String longestCommonPrefix(String[] strs) {
//Special case
if(strs.length == 0)
return "";
//Initial
Boolean prefix_match = false;
String prefix = strs[0];
//note: we will shorten the common prefix if not perfectly match
//Using Horizontal Scanning
for(int i=1; i< strs.length; i++){ //from the 1st string to the last string
while( prefix_match == false){
if(strs[i].indexOf(prefix) ==0) { //match: using string.indexOf(string)==0
prefix_match = true;
}
else{
prefix = prefix.substring(0, prefix.length()-1); //shorten prefix: using string.substring(0, length-1)
}
}
prefix_match = false;
}
return prefix;
}
}