[LeetCode]14.Longest Common Prefix

[제목]


Longest Common Prefix

 
Total Accepted: 8840 
Total Submissions: 33118 My 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
*     :http://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;
}

좋은 웹페이지 즐겨찾기