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.

    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 }
  • 相关阅读:
    flutter资料
    flutter兼论
    Dart 学习
    flutter简易教程
    全球15个顶级技术类博客
    Grunt压缩HTML和CSS
    用grunt搭建自动化的web前端开发环境-完整教程
    正确代码之-grunt
    grunt写一个px和rem互转的工具
    unslider使用方法1
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/10654827.html
Copyright © 2011-2022 走看看