欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

[leetcode]Longest Common Prefix

程序员文章站 2022-01-02 10:23:05
...

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.

寻找最长公共前缀,可以将后面的字符串依次与首个字符串比较,有不同的就停止比较,将相同的部分存入数组返回

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        if(strs.empty())
            return "";
        for(int i=0; i<strs[0].size(); i++)
        {
            for(int j=1; j<strs.size(); j++)
            {
                if(strs[j][i] != strs[0][i])
                    strs[0] = strs[0].substr(0,i);//复制长度为i的字符串
            }
        }
          return strs[0];  
        
    }
};

 

相关标签: leetcode