Click here to Skip to main content
15,881,803 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        
        Scanner sc=new Scanner(System.in);
        String A=sc.next();
        int mid = A.length()%2;
    
        if (mid%2==0){
            String S= A.substring(0,mid);
            String n="";
            for(int i=0;i<mid;i++){
                n=S.charAt(i)+n;
            }
            if(S==n) System.out.println("Yes");
            
        }
        if (mid%2!=0){
            String S= A.substring(0,mid-1);
            String n="";
            for(int i=0;i<mid;i++){
                 n=S.charAt(i)+n;
            }
            if(S.equals(n)) System.out.println("Yes");
            
        }
        
        
    }
}


What I have tried:

why string index is out of bound when i try to access a character at n=S.charAt(i)+n;

what should i do?
Posted
Updated 4-Jan-23 0:16am

You have a few problems:
1. Your calculation of the mid-point at line 10. It should be dividing by 2, not taking the remainder.
Java
int mid = A.length()/2; // get the number of characters in half the string

2. You use the value of mid to check if the string has an odd number of characters instead of the length of the original string.
3. When you build your string before comparing the two halves, the string n is just the reverse of the first half of the input. it should be the reverse of the second half.
 
Share this answer
 
Because S is guaranteed to be shorter than mid characters long:
String S= A.substring(0,mid-1);

If mid is 3, S is two characters, so when your loop generates indexes 0, 1, and 2 the final one is out of bounds.

To be honest, one single minute with the debugger would have shown you that 1/4 hour ago ... I strongly suggest you learn how to use it, it'll save you a huge amount of time in the future.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900