标签:code ble ase ems flight problems tps common 测试用例
14. 最长公共前缀---频率5次
输入:strs = ["flower","flow","flight"] 输出:"fl"
输入:strs = ["dog","racecar","car"]
输出:""
测试用例:["reflower","flow","flight"]
测试结果:""
这个没有模板思路。只是正常解题思路---对比基点,不断更新基点。
设置基点,然后不断循环string来比对基点。如果不是以基点开头的话,则就把基点从后往前减一。不断循环。直至结束
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs.length==0){return "";}
if(strs.length==1){return strs[0];}
String base = strs[0];
int index = 1;
while (index<strs.length){
//对比base和strs[index]值,取公共值更新base
int bal = base.length(); //拿到初始的基点长度
for (int i = 0; i < bal; i++) {
if(!strs[index].startsWith(base)){ //用字符串看是否是以基点开头的
base = base.substring(0, base.length()-1);
}
}
index++;
}
return base;
}
}
标签:code ble ase ems flight problems tps common 测试用例
原文地址:https://www.cnblogs.com/wfer/p/14655589.html