Leetcode_Easy_14

Posted IreneZh

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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() 是方法,加括号!!!

 

以上是关于Leetcode_Easy_14的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode_easy836. Rectangle Overlap

Leetcode_easy867. Transpose Matrix

Leetcode_easy868. Binary Gap

Leetcode_easy860. Lemonade Change

Leetcode_easy859. Buddy Strings

Leetcode_easy994. Rotting Oranges