[LeetCode]14. Longest Common Prefix

来源:互联网 发布:淘宝客进店买其他 编辑:程序博客网 时间:2024/06/05 10:39

[LeetCode]14. Longest Common Prefix

题目描述

这里写图片描述

思路

比较公共前缀,遍历即可

代码

#include <iostream>#include <string>#include <vector>using namespace std;class Solution {public:    string longestCommonPrefix(vector<string>& strs) {        if (strs.size() == 0)            return "";        if (strs.size() == 1)            return strs[0];        string res;        bool stop = false;        for (int j = 0; j < strs[0].size(); ++j) {            for (int i = 1; i < strs.size(); ++i) {                if (j >= strs[i].size()) {                    stop = true;                    break;                }                if (strs[i][j] != strs[0][j]) {                    stop = true;                    break;                }            }            if (stop)                break;            res += strs[0][j];        }        return res;    }};int main() {    vector<string> strs = { "abc", "", "ab" };    Solution s;    cout << s.longestCommonPrefix(strs) << endl;    system("pause");    return 0;}
原创粉丝点击