[leetcode]Longest Common Prefix
程序员文章站
2022-01-02 10:23:05
...
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string ""
.
Example 1:
Input: ["flower","flow","flight"] Output: "fl"
Example 2:
Input: ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z
.
寻找最长公共前缀,可以将后面的字符串依次与首个字符串比较,有不同的就停止比较,将相同的部分存入数组返回
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.empty())
return "";
for(int i=0; i<strs[0].size(); i++)
{
for(int j=1; j<strs.size(); j++)
{
if(strs[j][i] != strs[0][i])
strs[0] = strs[0].substr(0,i);//复制长度为i的字符串
}
}
return strs[0];
}
};
上一篇: 利用canvas生成图片验证码
推荐阅读
-
SPOJ1811 LCS - Longest Common Substring(后缀自动机)
-
LeetCode - 3.Longest Substring Without Repeating Characters(388ms)
-
【每日一道算法题】Leetcode之longest-increasing-path-in-a-matrix矩阵中的最长递增路径问题 Java dfs+记忆化
-
C# 写 LeetCode easy #14 Longest Common Prefix
-
LeetCode-32.Longest Valid Parentheses最长有效括号子串
-
Longest Valid Parentheses leetcode java (求最长有效匹配括号子串的长度)-动态规划
-
LeetCode 236 -- 二叉树的最近公共祖先 ( Lowest Common Ancestor of a Binary Tree ) ( C语言版 )
-
LeetCode 235--二叉搜索树的最近公共祖先 ( Lowest Common Ancestor of a Binary Search Tree ) ( C语言版 )
-
LeetCode 235. Lowest Common Ancestor of a Binary Search Tree 二叉搜索树
-
[Leetcode] 235. Lowest Common Ancestor of a Binary Search Tree