From 6197be81cf353fdb2fd6152a37c5cc8e59e3ff81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=80=90=E5=BC=A0=E9=91=AB=E3=80=91?= <974567732@qq.com> Date: Sat, 2 Mar 2019 21:47:14 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9C=80=E9=95=BF=E5=85=AC=E5=85=B1=E5=89=8D?= =?UTF-8?q?=E7=BC=80=E9=A2=98=E7=9B=AE=EF=BC=8C=E5=A2=9E=E5=8A=A0=E5=BC=82?= =?UTF-8?q?=E5=B8=B8=E8=BE=93=E5=85=A5=E6=A3=80=E6=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1、检查元素是否含有null 2、检查是否String数组是否为0 --- ...——几道常见的子符串算法题.md | 75 ++++++++++++------- 1 file changed, 47 insertions(+), 28 deletions(-) diff --git a/数据结构与算法/搞定BAT面试——几道常见的子符串算法题.md b/数据结构与算法/搞定BAT面试——几道常见的子符串算法题.md index b7b1c314..938f4a48 100644 --- a/数据结构与算法/搞定BAT面试——几道常见的子符串算法题.md +++ b/数据结构与算法/搞定BAT面试——几道常见的子符串算法题.md @@ -108,38 +108,57 @@ public class Solution { 思路很简单!先利用Arrays.sort(strs)为数组排序,再将数组第一个元素和最后一个元素的字符从前往后对比即可! ```java -//https://leetcode-cn.com/problems/longest-common-prefix/description/ public class Main { - public static String replaceSpace(String[] strs) { + public static String replaceSpace(String[] strs) { - // 数组长度 - int len = strs.length; - // 用于保存结果 - StringBuffer res = new StringBuffer(); - // 注意:=是赋值,==是判断 - if (strs == null || strs.length == 0) { - return ""; - } - // 给字符串数组的元素按照升序排序(包含数字的话,数字会排在前面) - Arrays.sort(strs); - int m = strs[0].length(); - int n = strs[len - 1].length(); - int num = Math.min(m, n); - for (int i = 0; i < num; i++) { - if (strs[0].charAt(i) == strs[len - 1].charAt(i)) { - res.append(strs[0].charAt(i)); - } else - break; + // 如果检查值不合法及就返回空串 + if (!chechStrs(strs)) { + return ""; + } + // 数组长度 + int len = strs.length; + // 用于保存结果 + StringBuilder res = new StringBuilder(); + // 给字符串数组的元素按照升序排序(包含数字的话,数字会排在前面) + Arrays.sort(strs); + int m = strs[0].length(); + int n = strs[len - 1].length(); + int num = Math.min(m, n); + for (int i = 0; i < num; i++) { + if (strs[0].charAt(i) == strs[len - 1].charAt(i)) { + res.append(strs[0].charAt(i)); + } else + break; - } - return res.toString(); + } + return res.toString(); - } - //测试 - public static void main(String[] args) { - String[] strs = { "customer", "car", "cat" }; - System.out.println(Main.replaceSpace(strs));//c - } + } + + private static boolean chechStrs(String[] strs) { + boolean flag = false; + // 注意:=是赋值,==是判断 + if (strs != null) { + // 遍历strs检查元素值 + for (int i = 0; i < strs.length; i++) { + if (strs[i] != null && strs[i].length() != 0) { + flag = true; + } else { + flag = false; + } + } + } + return flag; + } + + // 测试 + public static void main(String[] args) { + String[] strs = { "customer", "car", "cat" }; + // String[] strs = { "customer", "car", null };//空串 + // String[] strs = {};//空串 + // String[] strs = null;//空串 + System.out.println(Main.replaceSpace(strs));// c + } } ```