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
package fb; public class Palindrome {
public int countSubStr(String input) {
if (input==null || input.length()==0) return 0;
int res = 0;
for (int i=0; i<input.length(); i++) {
if (!isAlpha(input, i)) continue;
res += helper(input, i, i);
if (i < input.length()-1) res += helper(input, i, i+1);
}
return res;
} public int helper(String s, int l, int r) {
int res = 0;
while (l>=0 && r<s.length()) {
while (l>=0 && !isAlpha(s, l)) l--;
while (r<s.length() && !isAlpha(s, r)) r++;
if (l<0 || r>=s.length() || !isSame(s, l, r)) break;
else {
res++;
l--;
r++;
}
}
return res;
} public boolean isAlpha(String s, int i) {
char c = s.charAt(i);
if (c>='a' && c<='z' || c>='A' && c<='Z') return true;
return false;
} public boolean isSame(String s, int l, int r) {
char ll = s.charAt(l);
char rr = s.charAt(r);
ll = Character.isUpperCase(ll)? (char)(ll-'A'+'a') : ll;
rr = Character.isUpperCase(rr)? (char)(rr-'A'+'a') : rr;
return ll==rr;
} /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Palindrome sol = new Palindrome();
String input = "A@,b123a";
//String input = "Aba";
int res = sol.countSubStr(input);
System.out.println(res); } }