Fork me on GitHub

[leetcode-14-Longest Common Prefix]

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

 

posted @ 2017-05-11 16:12  hellowOOOrld  阅读(153)  评论(0编辑  收藏  举报