标签搜索

目 录CONTENT

文章目录

[leetcode]最长公共前缀题解

沙漠渔
2022-05-16 09:56:45 / 0 评论 / 0 点赞 / 675 阅读 / 1,590 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2022-05-16,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

题目说明

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 ""。

 

示例 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[]{}));
        }
    }
    
    0
    广告 广告

    评论区