赞
踩
packagealgorithm;importjava.util.ArrayList;importjava.util.Scanner;/*待解决问题:字符串分解时最后一个字母不分解
* 输出时不会输出所有可能的子list
*
* 原因是isPalindrome函数中,判断条件问题。
* 当字符串长度为1是middle算出来等于0
**/
public classStringPalindrome {public static voidmain(String[] args) {
Scanner scan= newScanner(System.in);//String s = scan.next();
String s = "aab";//System.out.println(s);
StringPalindrome aa = newStringPalindrome();
ArrayList> lists =aa.palindrome(s);
System.out.println(lists.toString());//System.out.println("test");
}public ArrayList>palindrome(String s){
ArrayList> lists = new ArrayList<>();
ArrayList list = new ArrayList<>();
partition(lists,list,s);//System.out.println("test"+lists.toString());
returnlists;
}public static void partition(ArrayList> lists, ArrayListlist, String s) {if(s == null || s.length() == 0) {
lists.add(new ArrayList<>(list));return;
}//System.out.println("test32" + s);
int len =s.length();for(int i = 0; i <= len; i++) {
String subStr= s.substring(0,i); //开始位置包含,结束位置不包含,当开始位置和结束位置相同时不能取出字符串
/*Returns a string that is a substring of this string.
Thesubstring begins at the specified beginIndex andextends to the character at index endIndex - 1.
Thus the length of the substring is endIndex-beginIndex.
Examples:
"hamburger".substring(4, 8) returns "urge"
"smiles".substring(1, 5) returns "mile"
Parameters:beginIndex the beginning index, inclusive.
endIndex the ending index, exclusive.Returns:the specified substring.
Throws:IndexOutOfBoundsException - if the beginIndex is negative,
or endIndex is larger than the length ofthis String object, or beginIndex is larger than endIndex.*/
//System.out.println("test1" + subStr);
if(isPalindrome(subStr)) {//System.out.print("test2" + isPalindrome(subStr));
list.add(subStr);
partition(lists,list,s.substring(i,len));
list.remove(list.size()-1);//System.out.println("test2" + list.toString());
}
}
}public static booleanisPalindrome(String s) {if(s == null || s.length() == 0)return false;int length =s.length();int middle = s.length()/2;for(int i = 0; i < middle; i++) {//如果判断条件改成 == return true 计算结果失败(当被判断字符串为空或者只有一个字符的时候无法判断middle等于0)
if(s.charAt(i) == s.charAt(length - i - 1)) {return true;
}
}return false;
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。