Last active
September 22, 2015 01:42
-
-
Save danielrobertson/afeafb6c61f9fe1169ee to your computer and use it in GitHub Desktop.
Given a string, print the number of palindromic substrings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Created by daniel robertson on 9/6/15. | |
*/ | |
import java.io.*; | |
import java.util.*; | |
import java.lang.StringBuffer; | |
public class NumberOfPalindromicSubstrings { | |
static int palindrome(String str) { | |
int result = 0; | |
int length = str.length(); | |
for(int i = 0; i < length; i++) { | |
for(int j = 1; j <= length - i; j++) { | |
if(isPalindrome(str.substring(i, i + j))) { | |
++result; | |
} | |
} | |
} | |
return result; | |
} | |
private static boolean isPalindrome(String s) { | |
StringBuffer stringBuffer = new StringBuffer(s); | |
StringBuffer reverse = new StringBuffer(s); | |
reverse.reverse(); | |
return stringBuffer.toString().equals(reverse.toString()); | |
} | |
public static void main(String[] args) throws IOException { | |
Scanner in = new Scanner(System.in); | |
int res; | |
String _str; | |
try { | |
_str = in.nextLine(); | |
} catch (Exception e) { | |
_str = null; | |
} | |
res = palindrome(_str); | |
System.out.println(res); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment