首页 > 其他 > 详细

[LeetCode] Longest Common Prefix

时间:2015-07-12 15:25:00      阅读:228      评论:0      收藏:0      [点我收藏+]

Use the strs[0] as the reference string and then compare it with the remaining strings from left to right. Once we find a string with length less than strs[0] or different letters in the corresponding position, we cannot move on and should return the longest common prefix string lcp. Each time we finish checking a position and have not returned, we add the letter at that position to lcp.

 1 class Solution {
 2 public:
 3     string longestCommonPrefix(vector<string>& strs) {
 4         if (strs.empty()) return "";
 5         string lcp = "";
 6         int m = strs.size(), n = strs[0].length();
 7         for (int i = 0; i < n; i++) {
 8             for (int j = 1; j < m; j++)
 9                 if (strs[j].length() == i || strs[j][i] != strs[0][i])
10                     return lcp;
11             lcp += strs[0][i];
12         }
13         return lcp;
14     }
15 };

 

[LeetCode] Longest Common Prefix

原文:http://www.cnblogs.com/jcliBlogger/p/4640887.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!