14. 最长公共前缀

  • ​​题目描述​​
  • ​​解题思路​​
  • ​​代码实现​​

题目描述

【LeetCode】第19天 - 14. 最长公共前缀_代码实现

解题思路

  • 首先假设公共前缀result = strs[0];
  • 然后将result与strs[1]进行比较,并更新result;
  • 继续比较result与strs[i]并更新result,直至遍历完strs。

代码实现

class Solution {
public String longestCommonPrefix(String[] strs) {
String result = strs[0];
int length = strs.length;
for(int i=1;i<length;i++){
//依次遍历strs,并更新result
result = longestTwoCommon(result,strs[i]);
}

return result;
}

//求两个字符串的公共前缀
public String longestTwoCommon(String s1,String s2){
int length = Math.min(s1.length(),s2.length());
int index = 0;
while(index<length && s1.charAt(index)==s2.charAt(index)){
++index;
}
return s1.substring(0,index);
}
}