LeetCode 14. Longest Common Prefix

Problem:

Write a function to find the longest common prefix string amongst an array of strings.

Solution:

Careful when strs has no Strings at all.

public class Solution {
    public String longestCommonPrefix(String[] strs) {
        String longest = "";
        int index = 0;
        if (strs.length == 0) return longest;
        while(index < strs[0].length()) {
            longest += strs[0].charAt(index++);
            for (int i = 1; i < strs.length; i++) {
                if (index > strs[i].length() || strs[i].charAt(index-1) != longest.charAt(index-1)) {
                    return longest.substring(0, index-1);
                }
            }
        }
        return longest;
    }
}