java输出字符串中所有的回文_字符串中所有的回文子串

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;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值