标签:
如果字符串数组只有一个,那么最长前缀就是它本身;如果有多个,我们把第一个设为当前最长前缀,拿当前最长前缀去和第二个比较,再选出最长前缀,一次往后即可!
代码:
#include<iostream> #include<string> #include<vector> using namespace std; string longestCommonPrefix(vector<string> &strs) { int L = strs.size(); if (L <1 ) { return ""; } string prefix = strs[0]; for (int i = 1; i < L; i++) { int LPre = prefix.size(); int LNow = strs[i].size(); int LQ = LPre>LNow ? LNow : LPre; int j; for (j = 0; j < LQ; j++) { if (prefix[j] != strs[i][j]) break; } if (j == LNow){ prefix = strs[i]; } else { prefix = strs[i].substr(0, j); } } return prefix; } int main() { vector<string> strs = {"asdqwer","as","asdklj"}; cout << longestCommonPrefix(strs) << endl; }
leetcode Longest Common Prefix
标签:
原文地址:http://www.cnblogs.com/chaiwentao/p/4417753.html