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/
View Code
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
相关文章推荐
- [leetcode] 14. Longest Common Prefix
- LeetCode----- 14.Longest Common Prefix
- [LeetCode]14. Longest Common Prefix
- [leetcode 14] Longest Common Prefix
- leetcode-14Longest Common Prefix
- leetcode 14. Longest Common Prefix
- leetcode【14题】Longest Common Prefix
- Leetcode-14. Longest Common Prefix
- [LeetCode-Java]14. Longest Common Prefix
- LeetCode 14. Longest Common Prefix
- Leetcode-14. Longest Common Prefix
- [leetcode]14. Longest Common Prefix
- Leetcode 14 Longest Common Prefix
- LeetCode 14: Longest Common Prefix
- 【LeetCode】C# 14、Longest Common Prefix
- LeetCode-14:Longest Common Prefix
- 【LeetCode】14 - Longest Common Prefix
- Leetcode——14. Longest Common Prefix
- LeetCode(14)--Longest Common Prefix
- leetcode 14. Longest Common Prefix