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.

 

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        int n = strs.size();
        if(n == 0)
            return "";
        int k = 0;
        string ans;
        bool flag = true;
        while(true) { // Kst char
            if(strs[0].size() < k+1)
                break;
            char ch = strs[0][k];
            for(int i=1; i<n && flag; i++) {
                if(strs[i].size() < k+1 || strs[i][k] != ch) {
                    flag = false;
                    break;
                }
            }
            if(flag) {
                ans.push_back(ch);
                k++;   
            } else {
                break;
            }
        }
        return ans;
    }
};

 

 posted on 2018-07-19 21:34  平和之心  阅读(108)  评论(0编辑  收藏  举报