题解 | #最长公共前缀#
最长公共前缀
https://www.nowcoder.com/practice/28eb3175488f4434a4a6207f6f484f47
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param strs string字符串一维数组 * @return string字符串 */ public static String twoLongestCommon(String x,String y){ int length = x.length()>y.length()? y.length():x.length();//取较小的字符串长度作为循环条件避免越界 String str = "";//保存公共字串的变量,并作为返回值返回。 for (int i = 0; i < length; i++) { if(x.charAt(i) == y.charAt(i)){ //比较两字符串相同索引位置的值,相等则加到str中 str+=x.charAt(i); } else { //只要两个同索引处的值不同直接返回str,不用再比了 return str; } } //循环结束后说明两个字符串相等,并且公共串添加完毕,返回str。 return str; } public static String longestCommonPrefix (String[] strs) { //将strs的元素传给twoLongest比较,并接收返回的串保存至后一位索引处。 //若strs为空或者长度为1,要单独考虑。 if (strs.length == 0){ return ""; } if(strs.length == 1){ return strs[0]; } //因为要比较下一个会加1,这边设置边界为length-1 for (int i = 0; i < strs.length-1; i++) { strs[i+1] = twoLongestCommon(strs[i] ,strs[i+1]); } //循环结束返回length-1处的值 return strs[strs.length-1]; } } //参考自csdn