将暴力进行到底!
vector判断是否为空: str.empty() 为空输出true,反之输出false。
删除string最后一个元素: pop_back();
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| // 最长公共前缀.cpp: 定义控制台应用程序的入口点。 //
#include "stdafx.h" #include <iostream> #include <vector> #include <string> using namespace std;
class Solution { public: string longestCommonPrefix(vector<string>& strs) { if (strs.empty()) return ""; string ans = strs[0]; if (strs.size() == 0 || strs.size() == 1) return ""; for (int i = 0; i < strs.size(); i++) { while (true) { int len1 = ans.size(); int len2 = strs[i].size(); //if (len1 == 0) //return " "; if (len1 == len2) { if (ans == strs[i]) break; else { ans.pop_back(); strs[i].pop_back(); } } else if (len1 > len2) { ans.pop_back(); } else strs[i].pop_back(); } } return ans; } };
int main() { Solution s; vector<string> strs; strs.push_back("dog"); strs.push_back("aig"); strs.push_back("dar"); cout << s.longestCommonPrefix(strs) << endl; return 0; }
|