首页 > 学院 > 开发设计 > 正文

Leet Code OJ 14. Longest Common Prefix

2019-11-10 22:12:12
字体:
来源:转载
供稿:网友

Write a function to find the longest common PRefix string amongst an array of strings.

编写一个函数来查找字符串数组中最长的公共前缀字符串。

代码

public String longestCommonPrefix(String[] strs) { if(strs == null || strs.length == 0) return ""; String pre = strs[0]; int i = 1; while(i < strs.length){ while(strs[i].indexOf(pre) != 0) pre = pre.substring(0,pre.length()-1); i++; } return pre;}

这里的思路是: 首先求2个的最长公共长缀,再用这个长缀去求第3个的最长公共长缀….


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表