LeetCode 14. Longest Common Prefix

来源:互联网 发布:道教地狱知乎 编辑:程序博客网 时间:2024/05/22 00:33

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


Compare one by one, get the common prefix.

    string longestCommonPrefix(vector<string>& strs) {    if(strs.size() == 0) return "";    if(strs.size() == 1) return strs[0];    string a = strs[0];    string res;    for(int i = 1; i < strs.size(); ++i) {        string tmp = "";        int j = 0;        int k = 0;        while(j < a.size() && k < strs[i].size()) {            if(a[j] == strs[i][k]) {                tmp= tmp + a[j];                j++; k++;            } else break;        }        a = tmp;        res = tmp;    }    return res;    }

Second Round:

To simplify this problem, since we are getting  the common prefix for all the input strings, we just need to first sort the input string alphabetically and compare the first and the last to check how much they overlap.

string longestCommonPrefix(vector<string>& strs) {  if(strs.size() < 1) return "";  sort(strs.begin(), strs.end());  string front = strs[0];  string end = strs.back();  for(int i = 0; i < front.size() && i < end.size(); ++i) {    if(front[i] != end[i]) break;  }  return front.substr(0, i);}


0 0
原创粉丝点击