[leetcode] Longest Common Prefix


Longest Common Prefix

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

tag: string

好久没一遍AC了。

直接暴力搜就好。

遍历整个字符串数组,每次查看位于n位置的字符是否相等,如果有一个不等则返回,如果全相等则n++。

class Solution {
public:
    string longestCommonPrefix(vector<string> &strs) {
        int n = 0;
        bool isFinish = false;
        if(strs.empty()){
            return string("");
        }
        while(!isFinish){
            char c;
            if(strs[0].size() == n){
                isFinish = true;
                break;
            }
            else{
                c = strs[0][n];
            }
            for(vector<string>::iterator it = strs.begin(); it != strs.end(); it++){
                if((*it).size() == n){
                    isFinish = true;
                    break;
                }
                else{
                    if(c != (*it)[n]){
                        isFinish = true;
                        break;
                    }
                }
            }
            if(!isFinish){
                n++;
            }
        }
        return strs[0].substr(0, n);
    }
};

Selection_017

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.