原题链接在这里:https://leetcode.com/problems/longest-common-prefix/
strs中的第一个字符串从i = 0 开始,取char, 取出char后,用来比较其他所有字符串,若是此时index i 已经等于其他字符串长度或者其他某个字符创相应位置上的char不同,说明已经走不下去了,就地返回res.
若其他字符串的响应位置都有char, 且相同,就把当前char加到res里,并且i++.
Note: string 的length函数是带括号的!是strs[j].length().
若需要用到character to string 的转换,可以使用Character.toString(char)函数。
AC Java:
public class Solution {
public String longestCommonPrefix(String[] strs) {
String res = new String();
if(strs == null || strs.length == 0){
return res;
}
int firStrLen = strs[0].length();
for(int i = 0; i<firStrLen; i++){
for(int j = 1;j<strs.length;j++){
if(strs[j].length() == i || strs[j].charAt(i)!=strs[0].charAt(i)){ //error
return res;
}
}
res = res + Character.toString(strs[0].charAt(i));
}
return res;
}
}