您的位置:首页 > 其它

LeetCode 14. Longest Common Prefix

2017-12-13 20:02 525 查看
https://leetcode.com/problems/longest-common-prefix/description/

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

Solution里提供了几种方法:横向扫描,纵向扫描,分治,二叉树搜索

我这用的纵向扫描所有字符串,只要找到这些串里第一个不匹配的字符,就找到最长公共前缀

注意此题与最长公共前缀短语的区别(http://www.cnblogs.com/pegasus923/p/5602046.html)

注意之前使用"i > strs[j].size() - 1"代替"i == strs[j].size()",结果出错out of range。因为string.size()是size_t类型,所以size()为0时,"strs[j].size() - 1"会变成"-1 + INTMAX"

注意substr的用法

string::substr - C++ Reference
http://www.cplusplus.com/reference/string/string/substr/
//
//  main.cpp
//  LeetCode
//
//  Created by Hao on 2017/3/16.
//  Copyright © 2017年 Hao. All rights reserved.
//

#include <iostream>
#include <cstring>
#include <vector>
using namespace std;

class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
// Empty vector
if (strs.empty()) return "";

// Vertical scanning
for (auto i = 0; i < strs[0].size(); i ++) {
for (auto j = 1; j < strs.size(); j ++) {
// Find the first string not matched
// Do not use "i > strs[j].size() - 1" as it's of type size_t, 0 - 1 = INT_MAX rather than -1
if (i == strs[j].size() || strs[j].at(i) != strs[0].at(i))
return strs[0].substr(0, i);
}
}

return strs[0];
}

};

int main(int argc, char* argv[])
{
Solution    testSolution;
string      result;

vector<vector<string>> sVec = {{"abab","aba",""}, {"test a short phrase", "test a slightly longer phrase"}};

/*
""
"test a s"
*/
for (auto str : sVec) {
result = testSolution.longestCommonPrefix(str);

cout << result << endl;
}

return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: