leetcode-14-字符串题-最长公共前缀 发表于 2020-03-14 | 分类于 数据结构与算法 题目 解法12345678910111213141516171819202122232425262728293031323334353637383940414243444546// 水平扫描,以第一个字符串为标准,依次比对后面的字符串class Solution{public: string longestCommonPrefix(vector<string> &strs) { string result; int vecSize = int(strs.size()); if (vecSize == 0) { return result; } if (vecSize == 1) { return strs[0]; } int min = INT_MAX; //获得最小长度 for (int index = 0; index < vecSize; ++index) { int strSize = strs[index].size(); if (min > strSize) { min = strSize; } } for (int increment = 1; increment <= min; ++increment) { string test = strs[0].substr(0, increment); for (int index = 1; index < vecSize; ++index) { string compared = strs[index].substr(0, increment); if (test != compared) { increment--; result = strs[0].substr(0, increment); return result; } } } result = strs[0].substr(0, min); return result; }};