leetcode第14题最长公共前缀

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-common-prefix
编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 ""。

示例 1:

输入: ["flower","flow","flight"]
输出: "fl"
示例 2:

输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。
首先对特殊情况进行考虑 如果字符串数组长度为0 那么我们直接对其进行返回“”
初始化最长公共前缀为字符串数组中第一个元素 从第二个元素开始 从前往后对该元素和目标元素进行遍历 相等的时候更新索引值 当字符不等的时候直接退出循环
如果中途出现了“” 那么直接返回
package com.lzh.simple;

import java.util.Scanner;

public class LongestCommonPrefix14 {
//最长公共前缀函数
public static String longestCommonPrefix(String[] strs){
//如果字符串数组长度为0 那么直接返回
if(strs.length==0){
return "";
}
String ans = strs[0];//初始化第一个元素为公共最长前缀
int i=1;//从第二个位置进行遍历字符串数组
while(i<strs.length){
int j=0;
for(;j<ans.length()&&j<strs[i].length();j++){//每个字符串中的数组的每一位从前向后进行比较
if(ans.charAt(j)!=strs[i].charAt(j)){//不同的时候直接跳出当前循环
break;
}
}
ans = ans.substring(0, j);//更新当前的最长前缀的值
i++;
if(ans.equals("")){//中途出现了最长公共前缀的时候那么直接返回
return ans;
}
}
return ans;
}
//测试
public static void main(String[] args) {
//Scanner scanner = new Scanner(System.in);
String[] strs = {"flower","flow","fly"};
String res = longestCommonPrefix(strs);
System.out.println(res);
}
}

原文地址:https://www.cnblogs.com/phantom576/p/11649068.html