天天看點

【String-easy】14. Longest Common Prefix 找到給定字元串數組的最長公共字首

1. 題目原址

https://leetcode.com/problems/longest-common-prefix/

2. 題目描述

【String-easy】14. Longest Common Prefix 找到給定字元串數組的最長公共字首

3. 題目大意

給定字元串數組,找到所有數組的最長公共字首

4. 解題思路

這個題可以再做一遍

5. AC代碼

class Solution {
    public String longestCommonPrefix(String[] strs) {
        if(strs == null || strs.length == 0)
            return new String();
        String prefix = strs[0];
        for(int i = 1; i < strs.length; i++) {
            while(strs[i].indexOf(prefix) != 0) {
                prefix = prefix.substring(0,prefix.length() - 1);
                if(prefix.isEmpty())
                    return "";
            }
        }
        return prefix;        
    }
}