这个简单,注意边界条件就行

public class Solution {
    public String longestCommonPrefix(String[] strs) {
        
        if (strs.length == 0)
            return "";
        
        String prefix = "";
        
        int p = 0;
        
        while(true) {
            
            char commonChar = 0;
            
            if (p >= strs[0].length()) {
                break;
            } else {
                commonChar = strs[0].charAt(p);
            }
            
            int i = 0;
            
            for (; i < strs.length; i++) {
                if (p >= strs[i].length()) {
                    break;
                }
                
                if (strs[i].charAt(p) != commonChar) {
                    break;
                }
            }
            
            if (i < strs.length) {
                break;
            } else {
                prefix = prefix + commonChar;
            }
            
            p++;
        }
        
        return prefix;
    }
}

chenatu
106 声望12 粉丝