[LeetCode] 14 - Longest Common Prefix

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

posted on 2015-08-28 11:09  tuituji  阅读(140)  评论(0编辑  收藏  举报

导航