FB面经 Prepare: All Palindromic Substrings

Given a string, calculate how many substring is palindrome. Ignore non-char characters. Ignore case;

Ex: "A@,b123a", equals "Aba", should output 4: "A", "b", "a", "Aba"

Spread from center: Like LC 5: longest palindromic substring

 1 package fb;
 2 
 3 public class Palindrome {
 4     public int countSubStr(String input) {
 5         if (input==null || input.length()==0) return 0;
 6         int res = 0;
 7         for (int i=0; i<input.length(); i++) {
 8             if (!isAlpha(input, i)) continue;
 9             res += helper(input, i, i);
10             if (i < input.length()-1) res += helper(input, i, i+1);
11         }
12         return res;
13     }
14     
15     public int helper(String s, int l, int r) {
16         int res = 0;
17         while (l>=0 && r<s.length()) {
18             while (l>=0 && !isAlpha(s, l)) l--;
19             while (r<s.length() && !isAlpha(s, r)) r++;
20             if (l<0 || r>=s.length() || !isSame(s, l, r)) break;
21             else {
22                 res++;
23                 l--;
24                 r++;
25             }
26         }
27         return res;
28     }
29     
30     public boolean isAlpha(String s, int i) {
31         char c = s.charAt(i);
32         if (c>='a' && c<='z' || c>='A' && c<='Z') return true;
33         return false;
34     }
35     
36     public boolean isSame(String s, int l, int r) {
37         char ll = s.charAt(l);
38         char rr = s.charAt(r);
39         ll = Character.isUpperCase(ll)? (char)(ll-'A'+'a') : ll;
40         rr = Character.isUpperCase(rr)? (char)(rr-'A'+'a') : rr;
41         return ll==rr;
42     }
43 
44     /**
45      * @param args
46      */
47     public static void main(String[] args) {
48         // TODO Auto-generated method stub
49         Palindrome sol = new Palindrome();
50         String input = "A@,b123a";
51         //String input = "Aba";
52         int res = sol.countSubStr(input);
53         System.out.println(res);
54 
55     }
56 
57 }
原文地址:https://www.cnblogs.com/EdwardLiu/p/6289368.html