Longest common prefix

    xiaoxiao2025-01-29  7

    1.题目 Write a function to find the longest common prefix string amongst an array of strings.

    2.解法 思路:先求得字符串数组中的最小长度minLen,最大的公共前部的长度为minLen,最多遍历字符串数组MinLen次即可。 遍历一次,中间遇到有不相同的就立即返回结果。

    public class Solution { public String longestCommonPrefix(String[] strs) { int size = strs.length; if(size == 0){ return ""; } String res = ""; int minLen = strs[0].length(); for(int i = 1; i < size; i++){ minLen = Math.min(strs[i].length(), minLen); } for(int i = 0; i < minLen; i++){ for(int j = 1; j < size; j++){ if(strs[j].charAt(i) != strs[0].charAt(i)){ return res; } } res += strs[0].charAt(i); } return res; } }
    转载请注明原文地址: https://ju.6miu.com/read-1295885.html
    最新回复(0)