当前位置:   article > 正文

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

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;

}

}

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/秋刀鱼在做梦/article/detail/799664
推荐阅读
相关标签
  

闽ICP备14008679号