Description:
Write a function to find the longest common prefix string amongst an array of strings.
Solution:
1. Firstly, judge if it is null.
2. To each String in String[], use String[i] to express.
3. if ( String[i].indexOf("pre") == 0 )
if true, return pre, else we create a substring from the String pre.
code:
class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) return "";
String pre = strs[0];
for (int i = 1; i < strs.length; i++){
while(strs[i].indexOf(pre) != 0){
pre = pre.substring(0, pre.length() - 1);
}
}
return pre;
}
}
Lesson learned:
1. String class function: indexOf
2. String class function: substring(int beginindex, int endindex)