2

Find the number of different palindromes you can make by changing exactly one ch...

 2 years ago
source link: https://www.codeproject.com/Questions/5319827/Find-the-number-of-different-palindromes
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

See more:

Copy Code
You are given a string s consisting of lowercase English letters. Find the number of different palindromes you can make by changing exactly one character from the string to some other lowercase English letter.
Input
The first and single line contains string s (1 ≤ |s| ≤ 10).
Output
Print the number of different palindromes you can make by changing exactly one character from the string to some other lowercase English letter.

Example:
Copy Code
Sample Input 1
abbb

Sample Output 1
2

Explanation:
The possible palindromes are:
    1. abba
    2. bbbb

========================================================================

Sample Input 2
abba

Sample Output 2
0
Copy Code
I'm doing my assignment. The given code passed all the hidden test cases except two test cases. I don't the hidden test cases what it should be that I haven't passed.


What I have tried:
Expand ▼   Copy Code
<pre>import java.util.*;

public class Main {
	      	
	static boolean isPalindrome(String str){
        String nstr="";
		char ch;
		for (int k=0; k<str.length(); k++)
	      {
	        ch= str.charAt(k);
	        nstr= ch+nstr;
	      }
          if(str.equals(nstr)) {
              return true;
          } else {
              return false;
          }
    }
	public static void main (String[] args) {
                      // Your code here
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine().toLowerCase();
        int j = str.length()-1;
        int len = str.length();
        int k = 0;
        String[] str1 = new String[len];
        if(len == 1 || isPalindrome(str)){
            System.out.print(0);
            return;
        }  else {
            for(int i=0; i< Math.floor(len/2); i++) {
                if(str.charAt(i) != str.charAt(j-i)) {
                    str1[k] = str.substring(0, j-i)+str.charAt(i)+str.substring(j-i+1, len); k++;
                    str1[k] = str.substring(0, i)+str.charAt(j-i)+str.substring(i+1, len); k++;        		
                }
            }
        }
        int count = 0;
        for(int i=0; i<str1.length; i++) {
        	if(str1[i] == null) {
        		break;
        	} else if(isPalindrome(str1[i])) {
        		count++;
        	}
        }
        System.out.println(count);  
	}
}

Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK