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;
        }
    }
  • 相关阅读:
    python_捕获异常
    requests二次封装_捕获异常
    python_flask模块
    python_redis模块
    python_requests模块
    使用pstack和gdb调试死锁
    如何编写go代码
    GDB调试命令手册
    core文件相关
    shared_ptr的线程安全性
  • 原文地址:https://www.cnblogs.com/trymorel/p/12525350.html
Copyright © 2011-2022 走看看