[leetcode-14-Longest Common Prefix]
Posted hellowOOOrld
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode-14-Longest Common Prefix]相关的知识,希望对你有一定的参考价值。
Write a function to find the longest common prefix string amongst an array of strings.
思路:
首先得到最短的字符串长度length,然后从0开始到length长度 挨个比较每一个字符是否相等。
string longestCommonPrefix(vector<string>& strs) { if (strs.size() == 0) return ""; int strLength = strs[0].size(); for (int i = 1; i < strs.size();i++) { strLength = min(strLength, (int)strs[i].size()); } int common = strLength; for (int i = 0; i < strLength; i++) { char temp = strs[0][i]; for (int j = 1; j < strs.size();j++) { if (strs[j][i] != temp) { common = i; i = strLength;//结束循环 break; } } } return strs[0].substr(0, common); }
以上是关于[leetcode-14-Longest Common Prefix]的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode 14. Longest Common Prefix
Leetcode 14 Longest Common Prefix
Leetcode14. Longest Common Prefix
LeetCode 14: Longest Common Prefix