【LeetCode】#14最长公共前缀(Longest Common Prefix)
题目描述
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。
示例
示例 1:
输入: [“flower”,“flow”,“flight”]
输出: “fl”
示例 2:
输入: [“dog”,“racecar”,“car”]
输出: “”
解释: 输入不存在公共前缀。
Description
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
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.
解法
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs.length==0)
return "";
StringBuilder sb = new StringBuilder();
int i=0;
while(true){
if(i==strs[0].length())
return sb.toString();
char ch = strs[0].charAt(i);
for(String str : strs){
if(i==str.length() || ch != str.charAt(i))
return sb.toString();
}
sb.append(ch);
i++;
}
}
}