[LeetCode] 14

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

class Solution {
  public:
    string longestCommonPrefix(vector<string>& strs) {
      string res;
      int nums = strs.size();
      if (nums == 0) {
        return res;
      }
      int len = (strs[0]).size();
      for (const string& str : strs) {
      if (str.size() < len) {
        len = str.size();
      }
    }

    for (int i = 0; i < len ; ++i) {
      char c = (strs[0])[i];
      bool same = true;
      for (const string& str : strs ) {
        if (str[i] != c) {
          same = false;
          break;
        }
      }
      if (!same) {
        break;
      }
      res.push_back(c);
    }
    return res;
  }
};

原文地址:https://www.cnblogs.com/shoemaker/p/4765922.html