文章标题

来源:互联网 发布:安卓编程用什么软件 编辑:程序博客网 时间:2024/06/07 23:58

Leetcode Algorithm 014. Longest Common Prefix

Longest Common Prefix
给定多个字符串,找出它们之间的最长公共前缀

解题思路

所有字符串的公共前缀必须同时出现在每个字符串的开头,比如"string""str""stable"的公共前缀是"st""abc""bcd""cdf"的公共前缀是""(空串)。

有了以上的了解,我们很容易可以想到,我们可以把第一个串作为基准串,遍历第一个串的每一个字符,并且与其它串上该位置的字符作匹配检验。当这个字符存在于所有的字符串中的时候,我们任务它属于公共前缀的一部分。

注意,当某个字符串的长度比基准串要短时,直接可以退出循环。当然,我们也可以把最短的那个字符串作为基准串,这样的循环结束的条件相对好写。

代码

#include<iostream>#include<vector>using namespace std;class Solution {public:    string longestCommonPrefix(vector<string>& strs) {        string result = "";        int n = strs.size();        if (n > 0) {            for (int i = 0; i < strs[0].size(); i++) {                char c = strs[0][i];                bool stop = false;                for (int j = 1; j < n; j++) {                    if (i == strs[j].size() || c != strs[j][i]) {                        stop = true;                        break;                    }                }                if (!stop) {                    result += c;                } else {                    break;                }            }        }        return result;    }};struct TestCase {    vector<string> strs;    void addStr(string str) {        strs.push_back(str);    }};int main() {    Solution s;    int t;    cin >> t;    TestCase testcase[t];    for (int i = 0; i < t; i++) {        int n;        cin >> n;        for (int j = 0; j < n; j++) {            string str;            cin >> str;            testcase[i].addStr(str);        }        string result = s.longestCommonPrefix(testcase[i].strs);        cout << result << endl;    }}

测试样例

第一行是样例的数目t,之后是每组样例,第一行是字符串的数目n,接下来的n行是n个字符串。

33stringstrstable2abcdefgh0

输出

st
原创粉丝点击