本文共 1054 字,大约阅读时间需要 3 分钟。
编写一个函数,用于查找字符串数组中的最长公共前缀。如果不存在公共前缀,则返回空字符串 ""。
示例1:输入:["flower","flow","flight"]输出:"fl"
示例2:输入:["dog","racecar","car"]输出:""
strs[0]
作为标兵字符串,作为参照。i
个字符。i
个字符。public class Solution { public String longestCommonPrefix(String[] strs) { if (strs == null || strs.length == 0) { return ""; } int len = strs[0].length(); for (int i = 0; i < len; i++) { for (int j = 1; j < strs.length; j++) { if (i >= strs[j].length() || strs[0].charAt(i) != strs[j].charAt(i)) { return strs[0].substring(0, i); } } } return strs[0]; }}
len
。i=0
开始遍历到 len-1
。通过以上步骤,可以高效地找到字符串数组的最长公共前缀。
转载地址:http://kofc.baihongyu.com/