Skip to content

Latest commit

 

History

History
38 lines (31 loc) · 1.35 KB

014.md

File metadata and controls

38 lines (31 loc) · 1.35 KB

14. Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.

#解析 要找到最长的公共前缀,我们只需从前往后依次比较字母是否相同即可。采用双层循环,第一层是字符串中字母的索引,第二层是字符串的索引。

需要注意的是:

  1. 我们要比较完所有字符串后才能确定这一位是否相同。
  2. 要考虑字符串长短不一,避免越界比较。若达到某一个字符串末尾,可立即返回结果。
  3. 一旦发现出现不同,可立即返回之前相同的前缀。

You are here! Your runtime beats 26.28% of cpp submissions.

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        int num = strs.size();        
        if(num == 0) return "";
        if(num == 1) return strs[0];
        
        string rst;
        for(int i = 0; ; ++i){
            int j = 0;
            for(; j < num - 1; ++j){
                if(i == strs[j].length() || i == strs[j + 1].length()){    //索引i已经到达字符串末尾
                    return rst;
                }                                
                if(!(strs[j][i] == strs[j+1][i])) return rst;    //出现不同
            }
            rst += strs[j][i];
        }
    }
};