Before I get into describing by problem I'd like to point out I found this question under c++
tag. But the solution of that question is already implemented in my code.
I am solving a problem from hackerrank. My code for that problem is logically correct but in some of the cases time limit exceeds.
Problem Statement
Given a string
S
, of lowercase letters, determine the index of the character whose removal will make aS
palindrome. If is already a palindrome or no such character exists, then print-1
. There will always be a valid solution, and any correct answer is acceptable. For example, if S = "bcbc", we can either remove 'b' at index 0 or 'c' at index 3.Input Format:
The first line contains an integer
T
, denoting the number of test cases.Each line
i
of theT
subsequent lines describes a test case in the form of a single string,Si
.Constraints:
Length of the string can be
100005
.Output Format:
Print an integer denoting the zero-indexed position of the character that makes
S
not a palindrome; ifS
is already a palindrome or no such character exists, print-1
.
As a solution my code is as following:
import java.io.*;
import java.util.*;
public class Solution {
public static boolean isPalindrom(String s){
int n = s.length();
for (int i=0;i<(n / 2);++i) {
if (s.charAt(i) != s.charAt(n - i - 1)) {
return false;
}
}
return true;
}
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
while(t-->0){
int flag = 0;
String sb = br.readLine().toString();
if(isPalindrom(sb)){
System.out.println("-1");
flag = 1;
}
for(int i=0;i<sb.length()&&flag==0;i++){
StringBuffer s = new StringBuffer(sb);
s.deleteCharAt(i);
if(isPalindrom(s.toString())){
System.out.println(i);
break;
}
}
}
}}
I've used best palindrome checker algorithm as described here. and also used BufferedReader
as described here. But time limit exceeds in some taste cases. How can I improve my code further?
Thanks in advance!