We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Case 1: See if we can completely erase String s and append String t. If we need to waste operations to reach k operations, we can do so when String s has no characters.
Case 2: See if we can convert String s to String t without completely erasing String s. We keep erasing charcters from String s until it becomes a prefix of String t. We then add the characters needed to turn String s into String t. If we need to waste operations to reach k operations, we can only do so in groups of 2 by doing an append and a delete.
importjava.util.Scanner;publicclassSolution{publicstaticvoidmain(String[]args){Scannerscan=newScanner(System.in);Strings=scan.next();Stringt=scan.next();intk=scan.nextInt();scan.close();System.out.println(canConvert(s,t,k)?"Yes":"No");}privatestaticbooleancanConvert(Strings,Stringt,intk){/* Case 1 */if(s.length()+t.length()<=k){returntrue;}/* Case 2 */inti=0;// represents index of 1st non-matching characterfor(;i<s.length()&&i<t.length();i++){if(s.charAt(i)!=t.charAt(i)){break;}}intminOperations=(s.length()-i)+(t.length()-i);returnk>=minOperations&&(k-minOperations)%2==0;}}
Append and Delete
You are viewing a single comment's thread. Return to all comments →
Java solution - passes 100% of test cases
From my HackerRank solutions.
Case 1: See if we can completely erase String s and append String t. If we need to waste operations to reach k operations, we can do so when String s has no characters.
Case 2: See if we can convert String s to String t without completely erasing String s. We keep erasing charcters from String s until it becomes a prefix of String t. We then add the characters needed to turn String s into String t. If we need to waste operations to reach k operations, we can only do so in groups of 2 by doing an append and a delete.
Let me know if you have any questions.