zoukankan      html  css  js  c++  java
  • LeetCode 14 Longest Common Prefix

    题目:

    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) {
            
            String res = "";
            
            if(strs.length==0) return res;
            
            Arrays.sort(strs);
            String b = strs[0];
            String e = strs[strs.length-1];
            
            
            for(int i=0;i<b.length();i++)
            {
                char c = b.charAt(i);
                
                if(i>=e.length()||e.charAt(i)!=b.charAt(i))
                        return res;
                res += c;
            }
            return res;
        }
    }
  • 相关阅读:
    mergeKLists
    generateParenthesis
    removeNthFromEnd
    Codeforces Round #632 (div.2) C. Eugene and an array
    Spring中@Import的三种情况
    自定义Spring Boot starter
    Java 注解
    Eclipse安装Lombok插件
    java 类加载系统
    Centos系统中忘了root密码怎么办
  • 原文地址:https://www.cnblogs.com/trymorel/p/12525350.html
Copyright © 2011-2022 走看看