天天看点

LeetCode——14. 最长公共前缀(C++)

题目链接:https://leetcode-cn.com/problems/longest-common-prefix/

#include <bits/stdc++.h>
using namespace std;

// 轮流比对,性能就很可以了 
class Solution
{
  public:
    string longestCommonPrefix(vector<string>& strs)
    {
      int nums = strs.size();  // 共有几个字符串
      if(nums == 0) return "";
      else if(nums == 1) return strs[0];
      int len = strs[0].length();
      for(int i = 1; i < nums; i++) len = strs[i].length() > len ? len : strs[i].length();
      int i, j;
      for(j = 0; j < len; j++)
      {
        for(i = 0; i < nums - 1; i++) if(strs[i][j] != strs[i+1][j]) break;
        if(i < nums - 1) break;
      }
      return strs[0].substr(0, j);
    }
};

int main()
{
  Solution sol;
  vector<string> v0 = {"flower","flow","flight"};
  cout<<sol.longestCommonPrefix(v0)<<endl;
  vector<string> v1 = {"dog","racecar","car"};
  cout<<sol.longestCommonPrefix(v1)<<endl;
  vector<string> v2 = {"flower","flow","flo"};
  cout<<sol.longestCommonPrefix(v2)<<endl;
  vector<string> v3 = {};
  cout<<sol.longestCommonPrefix(v3)<<endl;
  return 0;
}