最长公共前缀(Longest Common Prefix)

来源:互联网 发布:程序员三大浪漫 编辑:程序博客网 时间:2024/05/16 17:54

https://leetcode.com/problems/longest-common-prefix/description/

题目大意:Write a function to find the longest common prefix string amongst an array of strings.

在一组字符串中找最长公共前缀。

思路:vector结构体,最简单的思路就是最长前缀肯定也包含在第一个字符串里,故以第一个字符串为标准,都和后面的所有对比,遇到不同的改成“\0”,这样‘\0’前面的就是了。实际上这样做是不对的。可能他所给的字符串里本身就会有你作为标记的这个字符

#include<stdio.h>#include<algorithm>#include<iostream>#include<string.h>#include<limits.h>#include<vector>#include<map>using namespace std;string longestCommonPrefix(vector<string>& strs) {    if(strs.size()==0)        return "";    int size_str=strs.size();    string prefix=strs[0];    int i,l,j;    for(i=1;i<size_str;i++)    {        l=0;j=0;        while(prefix[l]!='*'&&l<prefix.size()&&l<strs[i].size()&&prefix[l]==strs[i][l]){            l++;        }        prefix[l]='*';    }    string b="";    for(i=0;prefix[i]!='*';i++)        b+=prefix[i];    return b;}int main(){    vector<string> strs;    string s;    for(int i=0;i<3;i++){        cin >> s;        strs.push_back(s);    }    string a=longestCommonPrefix(strs);    cout << a;}
最好的解法:刚才是横向比较,就是一个字符比完接着下一个,另一种就是纵向比较,就是先比较所有字符的第一个字母是否都一样,一样的话把这个一个字母赋给profix(string profix  = "")

    string longestCommonPrefix(vector<string>& strs) {        string prefix = "";        for(int idx=0; strs.size()>0; prefix+=strs[0][idx], idx++)            for(int i=0; i<strs.size(); i++)                if(idx >= strs[i].size() ||(i > 0 && strs[i][idx] != strs[i-1][idx]))                    return prefix;        return prefix;    }


阅读全文
0 0
原创粉丝点击