C++之最長前置詞字元串(13)---《那些奇怪的演算法》__web

來源:互聯網
上載者:User

參考:《one-day-one-leetcode》
需要求出多個字串的最長前置詞字元串,即求出最小的字串,然後求出最小字串的長度和對應的字串,然後在最短字串的長度內進行和其他字串的匹配即可。

#include <iostream>#include <string>#include <vector>using namespace std;string  longestCommonfix(vector<string>& strs){    int  i = 0, min_len = strs[i].length();    string min_str = strs[i];    string s = "";    ++i;    while (i < strs.size()){        if (min_len > strs[i].length()){            min_len = strs[i].length();            min_str = strs[i];        }        i++;    }    bool flag = false;    int j = 0;    while (j < min_len){        int count_j = 0;        for (int i = 0; i < strs.size(); i++){            if (strs[i][j] == min_str[j]){                count_j++;            }            else{                flag = true;                break;            }        }        if (flag == true) break;        if (count_j == strs.size()) s += min_str[j];        j++;    }    return s;}int main(){    string s[] = { "abc", "abcw", "abcab", "abc" };    vector<string> v;    for (int i = 0; i < sizeof(s) / sizeof(s[0]); i++){        v.push_back(s[i]);    }    cout << longestCommonfix(v) << endl;    return 0;}

運行結果:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.