Count Palindrome in String

来源:互联网 发布:蓝牙控制小车app源码 编辑:程序博客网 时间:2024/06/14 09:53

string 有多少palindrome substring。exp: 'aba' 返回4 , 'abba' 返回6

public class CountPalindrome {public int countPalindrome(String str){if(str == null || str.length() == 0) return 0;int count = 0;for(int i=0; i<str.length(); i++){//odd palindrome;count += find(str, i, i); // even palindromecount+= find(str, i, i+1);}return count;}public int find(String str, int start, int end){int count = 0;while(start>=0 && end<str.length()){if(str.charAt(start) == str.charAt(end)){count++;start--;end++;} else {break;}}return count;}public static void main(String[] args) {// TODO Auto-generated method stubCountPalindrome p = new CountPalindrome();System.out.println(p.countPalindrome("aba"));System.out.println(p.countPalindrome("abba"));}}


0 0
原创粉丝点击