首页 > 代码库 > Leetcode: Longest Common Prefix
Leetcode: Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
分析:这道题没什么好方法,暴力搜索比较即可,在用C++实现时有一个小trick就是"If pos is equal to the string length, the function returns a reference to the null character that follows the last character in the string, which shall not be modified" 所以不必先求出所有string的最小长度。代码如下:
class Solution {public: string longestCommonPrefix(vector<string> &strs) { if(strs.empty()) return ""; for(int i = 0; i < strs[0].length(); i++) for(int j = 1; j < strs.size(); j++){ if(strs[j][i] != strs[0][i]) return strs[0].substr(0,i); } return strs[0];//strs[0] is the longest common prefix }};
Leetcode: Longest Common Prefix
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。