https://leetcode.com/problems/longest-common-prefix/
Write a function to find the longest common prefix string amongst an array of strings.
public class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs.length == 0) {
return "";
}
int i = 0;
StringBuilder sb = new StringBuilder();
while (true) {
char ch = 0;
for (String s : strs) {
if (i == s.length()) {
return sb.toString();
}
if (ch == 0) {
ch = s.charAt(i);
}
if (ch != s.charAt(i)) {
return sb.toString();
}
}
sb.append(ch);
i++;
}
}
}
本博客介绍了一个函数,用于找出给定字符串数组中最长的公共前缀字符串。通过遍历数组中的每个字符串并比较字符,实现该功能。
296

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



