class Solution {
public String reverseWords(String s) {
int count = 0;
int current = 0;
StringBuilder build = new StringBuilder();
for(int i = 0; i< s.length(); i++){
count++;
current = count;
if(s.charAt(i) == ' '){
while(current > 0){
build.append(s.charAt(current - 1));
current--;
}
build.append(s.charAt(i));
}
}
return build.toString();
}
}
I am having trouble understanding why this doesn't work. I went through the entire code a couple of times but there seems to be an issue.
Input : "Let's take LeetCode contest"
my answer: " s'teL ekat s'teL edoCteeL ekat s'teL "
correct answer: "s'teL ekat edoCteeL tsetnoc"
whats going on?
There are several problems:
You set current to the current position, and then iterate down to 0 append characters. Instead of going down to 0, you iterate until the beginning of the last word. Alternative, iterate until the previous ' ' character.
You only append something after seeing a ' ' character. What will happen at the end of the sentences? As i goes over the letters in the last word, there will be no more ' ' characters, and so the last word will never get appended. To handle this case, you would need to add some logic after the for-loop to check if there is an unwritten word, and append it reversed.
A simpler approach is to take advantage of the StringBuilder's ability to insert characters at some position.
You could track the beginning position of the current word,
and as you iterate over the characters,
insert if it's not ' ',
or else append a ' ' and reset the insertion position.
StringBuilder build = new StringBuilder();
int current = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == ' ') {
build.append(' ');
current = i + 1;
} else {
build.insert(current, c);
}
}
return build.toString();
Use a StringBuilder to reverse each word in your String :
String input = "Let's take LeetCode contest";
String[] split = input.split(" +");
StringBuilder output = new StringBuilder();
for (int i = 0; i < split.length; i++) {
output.append(new StringBuilder(split[i]).reverse());
if(i<input.length()-1)
output.append(" ");
}
System.out.println(output);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With