Day 1.23
最长公共前缀
题目
思路
先令最长公共前缀为数组中的第一个元素a
,再循环遍历每个元素,使a
不断减小为:a
与遍历到的元素的公共前缀
代码
class Solution {
public String longestCommonPrefix(String[] strs) {
String a;
if(strs.length==0)return "";
a = strs[0];
for (String str : strs) {
// 若a已经减为"",则说明无公共前缀,直接返回
if (a == "") return a;
// 若a在当前str中匹配不上,则减少字符串a的长度,再次尝试匹配
while (!str.startsWith(a)) {
a = a.substring(0,a.length() - 1);
}
}
return a;
}
}