题目说明
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
示例 1:
输入:strs = ["flower","flow","flight"] 输出:"fl"
示例 2:
输入:strs = ["dog","racecar","car"] 输出:"" 解释:输入不存在公共前缀。
提示:
- 1 <= strs.length <= 200
- 0 <= strs[i].length <= 200
- strs[i] 仅由小写英文字母组成
Related Topics
解决方案
package leetcode.editor.cn;
/**
* 最长公共前缀
* @date 2022-01-25 16:19:26
* @author 沙漠渔
*/
public class 最长公共前缀{
static
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public String longestCommonPrefix(String[] strs) {
String com = "";
int pos = 0;
while (true){
for (String str : strs) {
if (pos >= str.length() || !str.startsWith(com)){
return com.substring(0, pos);
}
if (com.length() <= pos){
com = com.concat(String.valueOf(str.charAt(pos)));
}
}
pos++;
}
}
}
//leetcode submit region end(Prohibit modification and deletion)
static class ListNode {
int val;
ListNode next;
public ListNode(int val) { this.val = val; }
public ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
/**
* 最终测试主方法
*/
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.longestCommonPrefix(new String[]{"flower","flow","flight"}));
System.out.println(solution.longestCommonPrefix(new String[]{}));
}
}
评论区