LeetCode : Longest Common Prefix

来源:互联网 发布:mac 无法打开qq邮箱 编辑:程序博客网 时间:2024/06/07 23:12

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

Solution:

基本上也是一次写完通过的,只是刚开始把str.find(pre) != 0写成了str.find(pre) == string::npos。

class Solution {public:    string longestCommonPrefix(vector<string> &strs) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        string pre;        if(strs.size() == 0){            return pre;        }        if(strs.size() == 1){            return strs[0];        }        int nSize = strs.size();        string str1 = strs[0];        string str2 = strs[1];        for(int i = 0; i < str1.size() && i < str2.size(); ++i){            if(str1[i] == str2[i]){                pre += str1[i];            }            else{                break;            }        }        if(pre.size() == 0){            return pre;        }        for(int i = 2; i < nSize; ++i){            string str = strs[i];            while(str.find(pre) != 0 && pre.size() > 0){                pre = pre.substr(0, pre.size() - 1);            }            if(pre.size() == 0){                return pre;            }        }        return pre;    }};