码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 14 - Longest Common Prefix

时间:2015-08-28 12:47:23      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

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

[LeetCode] 14 - Longest Common Prefix

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!