首页 > 其他 > 详细

[LeetCode] 14 - Longest Common Prefix

时间:2015-08-28 12:45:25      阅读:103      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!