14. Longest Common Prefix(Leetcode每日一题-2020.06.15)

Problem

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 “”.

All given inputs are in lowercase letters a-z.

Example1

Input: [“flower”,“flow”,“flight”]
Output: “fl”

Example2

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

Solution

class Solution {
public:
    string longestCommonPrefix(vector<string> &strs) {
        if(strs.empty())
            return "";
        string ret = strs[0];
        for(auto &str:strs)
        {
            int len =min(ret.length(),str.length());

            int i = 0;
            while(i<len)
            {
                if(ret[i] != str[i])
                    break;
                ++i;
            }

            if(i < ret.length())
                ret = ret.substr(0,i);
            
        }

        return ret;
    }

你可能感兴趣的:(leetcode字符串)