LeetCode(14)——Longest Common Prefix

題目:

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

If there is no common prefix, return an empty string "".

Example 1:

Input: ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Note:

All given inputs are in lowercase letters a-z.

 

AC:

public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        
        int strsLen = strs.length;
        int len = strs[0].length();
        
        int index = 0;
        
        while (index < len) {
            char ch = strs[0].charAt(index);
        
            for (int i = 1; i < strsLen; i++) {
                if (index >= strs[i].length() || strs[i].charAt(index) != ch) {
                    return strs[0].substring(0, index);
                }
            }
            index++;
        }

        
        if (index == len) {
            return strs[0].substring(0, index);
        }
        
        
        return "";
        
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章