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

[leetcode-14-Longest Common Prefix]

时间:2017-05-11 17:00:31      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:结束   log   开始   string   amp   break   prefix   vector   min   

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

思路:

首先得到最短的字符串长度length,然后从0开始到length长度 挨个比较每一个字符是否相等。

string longestCommonPrefix(vector<string>& strs)
     {
         if (strs.size() == 0) return "";
         int strLength = strs[0].size();
         for (int i = 1; i < strs.size();i++)
         {
             strLength = min(strLength, (int)strs[i].size());
         }
         int common = strLength;
         for (int i = 0; i < strLength; i++)
         {
             char temp = strs[0][i];
             for (int j = 1; j < strs.size();j++)
             {
                 if (strs[j][i] != temp)
                 {
                     common = i;
                     i = strLength;//结束循环
                     break;
                 }
             }
         }
         return strs[0].substr(0, common);
     }

 

[leetcode-14-Longest Common Prefix]

标签:结束   log   开始   string   amp   break   prefix   vector   min   

原文地址:http://www.cnblogs.com/hellowooorld/p/6841426.html

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