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

【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;
    }
};
 

 

posted @ 2019-01-05 15:57  wikiwen  阅读(311)  评论(0编辑  收藏