https://leetcode.com/problems/reverse-words-in-a-string-iii
https://discuss.leetcode.com/topic/85784/c-java-clean-code
https://discuss.leetcode.com/topic/85744/java-solution
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not be any extra space in the string.
https://discuss.leetcode.com/topic/85911/easiest-java-solution-9ms-similar-to-reverse-words-in-a-string-ii
Step 1. Convert the string to char[] array
Step 2. Whenever I encounter a space ' ' , I call the reverse function ( just to keep the code clean )
Step 3. Repeat till the end!
Step 2. Whenever I encounter a space ' ' , I call the reverse function ( just to keep the code clean )
Step 3. Repeat till the end!
public String reverseWords(String s)
{
char[] s1 = s.toCharArray();
int i = 0;
for(int j = 0; j < s1.length; j++)
{
if(s1[j] == ' ')
{
reverse(s1, i, j - 1);
i = j + 1;
}
}
reverse(s1, i, s1.length - 1);
return new String(s1);
}
public void reverse(char[] s, int l, int r)
{
while(l < r)
{
char temp = s[l];
s[l] = s[r];
s[r] = temp;
l++; r--;
}
}
Yes your solution will work. But I think my solution will be faster because you are checking (j == n) every time and performing i = j + 1 for the last call which is unnecessary.
my solution - Run time : 9ms (94.42 %)
yours - Run time : 10ms (88.72 %)
yours - Run time : 10ms (88.72 %)
public String reverseWords(String s) {
int n = s.length();
char[] c = s.toCharArray();
for (int i = 0, j = 1; j <= n; j++) {
if (j == n || c[j] == ' ') {
reverse(c, i, j-1);
i = j+1;
}
}
return new String(c);
}
private void reverse(char[] c, int i, int j) {
while (i < j) {
char temp = c[i];
c[i] = c[j];
c[j] = temp;
i++; j--;
}
}
public String reverseWords(String s) {
char[] ca = s.toCharArray();
for (int i = 0; i < ca.length; i++) {
if (ca[i] != ' ') { // when i is a non-space
int j = i;
while (j + 1 < ca.length && ca[j + 1] != ' ') { j++; } // move j to the end of the word
reverse(ca, i, j);
i = j;
}
}
return new String(ca);
}
private void reverse(char[] ca, int i, int j) {
for (; i < j; i++, j--) {
char tmp = ca[i];
ca[i] = ca[j];
ca[j] = tmp;
}
}
https://discuss.leetcode.com/topic/85744/java-solution
public String reverseWords(String s) {
String[] strs = s.split(" ");
StringBuffer sb = new StringBuffer();
for(String str: strs){
StringBuffer temp = new StringBuffer(str);
sb.append(temp.reverse());
sb.append(" ");
}
sb.setLength(sb.length()-1);
return sb.toString();
}