LeetCode第19天 - 14. 最长公共前缀

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode第19天 - 14. 最长公共前缀相关的知识,希望对你有一定的参考价值。


14. 最长公共前缀

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

题目描述

【LeetCode】第19天

解题思路

  • 首先假设公共前缀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);


以上是关于LeetCode第19天 - 14. 最长公共前缀的主要内容,如果未能解决你的问题,请参考以下文章

leetCode第14题——最长公共前缀

python(leetcode)-14最长公共前缀

Leetcode练习(Python):字符串类:第14题:最长公共前缀:编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。

Leetcode练习(Python):字符串类:第14题:最长公共前缀:编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。

LeetCode第14题:最长公共前缀

LeetCode14-最长公共前缀(水题)