Hello! So I’m doing a 30 day coding challenge where I solve a few questions every day and thought of posting them here on my blog so that you guys can join the challenge too!
Welcome to Coding challenge Day 23: Problem 1! Be sure to post your answers, queries etc in the comments!
Problem: Write method takes a single string parameter and returns a scrambled version of that string.
(a) Write the method scrambleWord, which takes a given word and returns a string that contains a scrambled version of the word according to the following rules.
1. The scrambling process begins at the first letter of the word and continues from left to right.
2. If two consecutive letters consist of an “A” followed by a letter that is not an “A”, then the two letters are swapped in the resulting string.
3. Once the letters in two adjacent positions have been swapped, neither of those two positions can be involved in a future swap.
WORD | Scrambled word |
TAN | TNA |
ABRACADABRA | BARCADABARA |
WHOA | WHOA |
AARDVARK | ARADVRAK |
EGGS | EGGS |
A | A |
Solution:
public class scrambleproblem {
public static String Scrambleword (String str){
String scrambled="";
for(int i=0; i<str.length(); i++){
char c= str.charAt(i);
if(i < (str.length()-1) && c=='A'){
scrambled+= (char)str.charAt(i+1) + "A";
i++;
}
else{
scrambled+=c;
}
}
return scrambled;
}
}
Happy Learning!!