I am trying to solve this question on leetcode and I have tried running it on pen and paper and it seems I should get my answer. But my code is showing TLE in JAVA. Can someone suggest me how to get rid of TLE and submit my solution? Why is it showing TLE?
Question: Check if string is transformable with substring sort operations.
My code:
class Solution {
public boolean isTransformable(String s, String t) {
int p1 = s.length()-1;
int p2 = t.length()-1;
int p3 = s.length()-1;
while(p1>-1){
if(intAt(s,p1)==intAt(t,p2)){
p1--;
p2--;
}else{
while(intAt(s,p3)!=intAt(t,p2)){
p3--;
if(p3==0 && intAt(s,p3)!=intAt(t,p2)){
return false;
}
}
swap(s,intAt(s,p1),intAt(s,p3));
}
}
if(s.equals(t)){
return true;
}
return false;
}
public int intAt(String s, int index)
{
int r = Integer.parseInt(s.substring(index, index 1));
return r;
}
void swap(String s, int first, int second) {
int temp = first;
first = second;
second = temp;
}
}
CodePudding user response:
I have got my answer. Thanks to everyone who commented and edited my question. Strings are immutable. My swap function does nothing.
CodePudding user response:
I think you are trying too hard. You should just check if it's possible to create string t, using the numbers from string s. (Swapping is not needed).
First, check if both string have the same length.
Second, check for each number in string S if, this number is present in string t. Remove this number if present from string t.
- If by any case false comes up, you should return false.
Third, make sure string t is empty when you are done looping though s.
If no errors occurred, you should return true;
You TLE errors is probably there because you are taking too long to do the check. (not a java error).