文章 224
评论 6
浏览 200770
String - 14. Longest Common Prefix

String - 14. Longest Common Prefix

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.

思路:

leetcode 一共有四种解法,这里就只写第一种,就是以一个string为标准,不断的调用api接口判断子串是否在字符串开头(注意,这一题只用判断从索引为0开始的公共字符串)

代码:

java:

class Solution {
    public String longestCommonPrefix(String[] strs) {
        if (strs == null || 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;
    }
}

标题:String - 14. Longest Common Prefix
作者:michael
地址:https://www.bitbo-liuyang.com/articles/2019/06/27/1561648557520.html

Nothing just happens, it's all part of a plan.

取消