閱讀702 返回首頁    go 阿裏雲 go 技術社區[雲棲]


[LeetCode]14.Longest Common Prefix

【題目】

Longest Common Prefix

 Total Accepted: 8840 Total Submissions: 33118My Submissions

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

【分析】

從0開始,對每一個位置比較所有的字符串,如果有不相等的則停止匹配。

【代碼】

/*--------------------------------------------------------------
*   日期:2015-08-30
*   作者:SJF0115
*   題目: 14.Longest Common Prefix
*   來源:https://oj.leetcode.com/problems/longest-common-prefix/
*   結果:AC
*   來源:LeetCode
------------------------------------------------------------*/
#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
    string longestCommonPrefix(vector<string> &strs) {
        int size = strs.size();
        if(size <= 0){
            return "";
        }//if
        if(size == 1){
            return strs[0];
        }//if
        bool isSucess = true;
        int size1 = strs[0].size();
        for(int i = 0;i < size1;++i){
            for(int j = 1;j < size;++j){
                // 匹配失敗
                if(i >= strs[j].size() || strs[0][i] != strs[j][i]){
                    isSucess = false;
                    break;
                }//if
            }//for
            if(!isSucess){
                return strs[0].substr(0,i);
            }//if
        }//for
        return strs[0];
    }
};

int main() {
    Solution solution;
    string str1("abcdef");
    string str2("adcdefd");
    string str3("abcdefe");
    vector<string> vec;
    vec.push_back(str1);
    vec.push_back(str2);
    vec.push_back(str3);
    string result = solution.longestCommonPrefix(vec);
    cout<<result<<endl;
    return 0;
}



最後更新:2017-04-03 12:56:12

  上一篇:go vi 搜索命令 搜索字符串
  下一篇:go pyramid學習筆記3-創建注冊頁麵