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/
- string::substr - C++ Reference
1 // 2 // main.cpp 3 // LeetCode 4 // 5 // Created by Hao on 2017/3/16. 6 // Copyright © 2017年 Hao. All rights reserved. 7 // 8 9 #include <iostream> 10 #include <cstring> 11 #include <vector> 12 using namespace std; 13 14 class Solution { 15 public: 16 string longestCommonPrefix(vector<string>& strs) { 17 // Empty vector 18 if (strs.empty()) return ""; 19 20 // Vertical scanning 21 for (auto i = 0; i < strs[0].size(); i ++) { 22 for (auto j = 1; j < strs.size(); j ++) { 23 // Find the first string not matched 24 // Do not use "i > strs[j].size() - 1" as it's of type size_t, 0 - 1 = INT_MAX rather than -1 25 if (i == strs[j].size() || strs[j].at(i) != strs[0].at(i)) 26 return strs[0].substr(0, i); 27 } 28 } 29 30 return strs[0]; 31 } 32 33 }; 34 35 int main(int argc, char* argv[]) 36 { 37 Solution testSolution; 38 string result; 39 40 vector<vector<string>> sVec = {{"abab","aba",""}, {"test a short phrase", "test a slightly longer phrase"}}; 41 42 /* 43 "" 44 "test a s" 45 */ 46 for (auto str : sVec) { 47 result = testSolution.longestCommonPrefix(str); 48 49 cout << result << endl; 50 } 51 52 return 0; 53 }