'Test case failed in executing special palindromic strings program

  • I am trying to solve hacker rank question for counting number of special palindrome strings contained within a string
  • To be considered for Special palindrome strings, all the characters should be same, as well as all characters except middle one are the same
  • Say for example, string = asasd, then palindromic strings are {a, s, a, s, d, asa, sas}
  • In this program, two test cases are passed with strings asasd and aaaa respectively
  • One test case failed for the string abcbaba
  • I researched for checking second condition but I am struck with the execution
  • can you guys help me to solve issue with your suggestions
  • providing entire code below:
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class MyClass {
    public static void main(String args[]) {
        int counter=0;
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt(); // read an integer from input stream.
        String s = scanner.next();
        char string_array[] = s.toCharArray();
        for(int i=0; i<s.length(); i++){
            for(int j=i; j<=s.length(); j++){
                if(i != j){
                    String s1 = s.substring(i,j);
                    String rev = "";
                    for(int z=0; z<s1.length(); z++){
                    rev = rev + s1.charAt(s1.length()-1-z);
                    }
                    //System.out.println("s1=" + s1 +  "rev=" + rev);
                    int count = s1.compareTo(rev);
                    if(count == 0){
                    counter++;
                }
                }
            }

        }
        System.out.println(counter);
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source