解题的有两个关键,一个是单例模式如何实现(创建一个对象,让构造函数为 private,这样该类就不会被实例化,再获取唯一可用对象 ),一个是对spring对象的方法有一个比较清楚的了解,比如:
Sting s = "aaaaaaa";
String[] strings = spring.split("a");
此时strings数组是空的(因为都是分隔符). 这一特点恰好可以利用起来作为判断 L的依据.
-
先用单例模式编写方法类
package com.ryan; import org.apache.commons.lang3.StringUtils; public class Tool { //创建一个对象
private static Tool tool; //让构造函数为 private,这样该类就不会被实例化
private Tool(){} //获取唯一可用对象
public static Tool getTool() { if (tool == null) { tool = new Tool(); } return tool; } //编写用来解题的方法
public static String compress(String s){ String result = ""; if (StringUtils.isBlank(s)){ result ="你输入为空!"; }else if (s.contains(" ")){ result ="请不要输入空格!"; }else { int length = s.length(); System.out.println("length: "+length); int count = 0; for (int i= 1;i<=length;i++){ String[] strings1 = s.split(s.substring(0,i)); if (strings1.length==0){ System.out.println("切分到"+i); count = i; break; } } result = length/count + s.substring(0,count); } return result; } }
-
再编写主类
package com.ryan; public class Test1 { public static void main(String[] args) { String s = "aaaaaa"; String result = ""; Tool tool = Tool.getTool(); result = tool.compress(s); System.out.println(result); } }
大功告成.