zoukankan      html  css  js  c++  java
  • Leetcode_Easy_14

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

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

    class Solution {
        public String longestCommonPrefix(String[] strs) {
            if (strs.length == 0)
                return "";
            String prefix = strs[0];
            for (int i = 1; i < strs.length; i++){
                while (strs[i].indexOf(prefix) != 0){
                    prefix = prefix.substring(0, prefix.length()-1);
                    if (prefix.isEmpty())
                        return "";
                }
                
            }
            return prefix;
        }
    }

    知识点1:

    方法:String.indexOf(String)

    while (strs[i]. indexOf(prefix) != 0) {...}

    这个循环用来比较两个字符串,直到找到完全相同的前缀(因为prefix永远从0,末尾长度-1)

    如果两个字符串不一样,比如String a = "letter"; String b = "love", 那么 a.indexOf(b) = -1; 返回值是int -1。

    如果两个字符串相同,返回值就是0.

    如果 String a = "letter"; a.indexOf('t') --> 返回值是2(第一次出现的位置)

    知识点2:

    int[] arr = new int[3];
    System.out.println(arr.length);//数组长度
     
    String str = "abc";
    System.out.println(str.length());//字符串长度

    数字: Array.length 是属性,不加括号!!!

    字符串:String.length() 是方法,加括号!!!

  • 相关阅读:
    WEB API&API
    event flow
    JS-for的衍生对象
    JS-function
    Object Constructor
    前端发展史
    JavaScript中document.getElementById和document.write
    正则表达式把Paul换成Ringo
    11th blog
    10th week blog
  • 原文地址:https://www.cnblogs.com/Jessiezyr/p/10565217.html
Copyright © 2011-2022 走看看