当前位置:网站首页>Leetcode longest public prefix

Leetcode longest public prefix

2022-07-07 05:00:00 kt1776133839

Title Description :

Write a function to find the longest common prefix in the string array .

If no common prefix exists , Returns an empty string "".

Examples :

Example 1:

Input :strs = ["flower","flow","flight"]
Output :"fl"

Example 2:

Input :strs = ["dog","racecar","car"]
Output :""
explain : Input does not have a common prefix .

Tips :

    1 <= strs.length <= 200
    0 <= strs[i].length <= 200
    strs[i] It's only made up of lowercase letters

Java Program :

class Solution {
    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        String prefix = strs[0];
        int count = strs.length;
        for (int i = 1; i < count; i++) {
            prefix = longestCommonPrefix(prefix, strs[i]);
            if (prefix.length() == 0) {
                break;
            }
        }
        return prefix;
    }

    public String longestCommonPrefix(String str1, String str2) {
        int length = Math.min(str1.length(), str2.length());
        int index = 0;
        while (index < length && str1.charAt(index) == str2.charAt(index)) {
            index++;
        }
        return str1.substring(0, index);
    }
}

原网站

版权声明
本文为[kt1776133839]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130740485387.html