首页 > 其他 > 详细

【LeetCode & 剑指offer刷题】字符串题10:Longest Common Prefix

时间:2019-01-05 16:10:48      阅读:165      评论:0      收藏:0      [点我收藏+]

【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)

 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.

C++
 
//问题:各字符串最长公共前缀
/*
class Solution
{
public:
    string longestCommonPrefix(vector<string>& strs)
    {
        if(strs.size() == 0) return ""; //返回空串
        if(strs.size() == 1) return strs[0]; //返回自身
       
        string res = strs[0]; //初始化
        int length = res.size(); //公共前缀的长度
        for(int i = 1; i<strs.size(); i++) //从第二个单词开始遍历
        {
            int temp = -1;
            for(int j = 0; j<length && j<strs[i].size(); j++)//遍历单词内字符
            {
                if(strs[i][j] == res[j] ) temp  = j; //保存当前索引
                else break; //一旦不相等就退出循环
            }
            length = temp + 1;
        }
        res[length] = ‘\0‘; //打上结束字符
       
        return res;
    }
};*/
//也可用string的成员函数substr简化程序
class Solution
{
public:
    string longestCommonPrefix(vector<string>& strs)
    {
        if(strs.empty()) return ""; //返回空串
       
        string prefix = strs[0];
        for(int i = 1; i<strs.size(); i++)
        {
            for(int j = 0; j<prefix.size(); j++)
            {
                if(strs[i][j] != prefix[j])
                {
                    prefix = prefix.substr(0, j); //公共前缀更新,substr中区间为前闭后开,故当遇到第一个不相等字符后,就将前面相等的字符复制过去,之后j<prefix.size()无法满足,退出循环。
                }
            }
        }
       
       
        return prefix;
    }
};
 

 

【LeetCode & 剑指offer刷题】字符串题10:Longest Common Prefix

原文:https://www.cnblogs.com/wikiwen/p/10224858.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!