解題的有兩個關鍵,一個是單例模式如何實現(創建一個對象,讓構造函數為 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); } }
大功告成.