Tuesday, June 3, 2014

LeetCode Longest Common Prefix

Here we need check the length of the string in the array.

public String longestCommonPrefix(String[] strs) {
        if (strs== null || strs.length == 0) return "";
        StringBuilder sb = new StringBuilder();
for (int i = 0; i < strs[0].length(); i++) {
char temp = strs[0].charAt(i);
for (int j = 0; j < strs.length; j++) {

if (i >= strs[j].length() || temp != strs[j].charAt(i)) {
return sb.toString();
}
}
sb.append(temp);
}
return sb.toString();
    }

No comments:

Post a Comment