Longest Common Prefix (E)
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(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
String ans = "";
for (int i = 0; i < strs[0].length(); i++) {
char c = strs[0].charAt(i);
for (int j = 1; j < strs.length; j++) {
if (i == strs[j].length() || strs[j].charAt(i) != c) {
return ans;
}
}
ans += c;
}
return ans;
}
}
本文介绍了一种寻找一组字符串中最长公共前缀的有效算法。通过对比每个字符串的字符,逐步构建公共前缀,直至所有字符串无法匹配为止。适用于字符串处理和算法设计的学习者。
307

被折叠的 条评论
为什么被折叠?



