close

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: strs = ["flower","flow","flight"]
Output: "fl"

Example 2:

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

 

Constraints:

  • 1 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] consists of only lower-case English letters.

 

 

 

 

 

 

string longestCommonPrefix(vector<string>& strs) {
        string prefix = "";
        int len = 0;
        while (strs[0].size() > len){ 
            char cur = strs[0][len];
            for (int i = 1; i < strs.size(); i++){
                if (!((strs[i].size() > len) && (strs[i][len] == cur)))
                    return prefix;
            }
            prefix += cur;
            len ++;
        }
        return prefix;
    }

 

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 Eric 的頭像
    Eric

    一個小小工程師的心情抒發天地

    Eric 發表在 痞客邦 留言(0) 人氣()