• [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.

    Solution1:  

    Compare characters from top to bottom on the same column (same character index of the strings) before moving on to the next column.

    code

     1 /*
     2 Time complexity : O(S), where S is the sum of all characters in all strings. 
     3 Space complexity : O(1). We only used constant extra space. 
     4 */
     5 class Solution {
     6     public String longestCommonPrefix(String[] strs) {
     7         if (strs.length == 0)  return "";
     8         for (int i = 0; i < strs[0].length(); i++) {
     9             char c = strs[0].charAt(i);
    10             for (int j = 1; j < strs.length; j++) {
    11                 if (i == strs[j].length() || strs[j].charAt(i) != c) { // 除str[0]外的一个String被扫完了
    12                     return strs[0].substring(0, i);
    13                 }
    14             }
    15         }
    16         // 有可能strs[0]扫完了都没碰到垂直方向不相同的字符
    17         return strs[0];
    18     }
    19 }
  • 相关阅读:
    elasticsearch 不能通过9200端口访问
    elasticsearch 2.0+ 安装 Marvel
    修改es最大返回结果数
    ElasticSearch的Marvel更新license
    python-execjs(调用js)
    爬取豆瓣电影排名的代码以及思路
    docker的安装
    mysql主从同步
    Docker配置yapi接口
    第24课
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/10654827.html
Copyright © 2020-2023  润新知