Skip to main content

Reverse Words in a String II

LeetCode Link

Problem Description​

Visit LeetCode for the full problem description.


Solutions​

Solution 1: C# (Best: 476 ms)​

MetricValue
Runtime476 ms
MemoryN/A
Date2018-07-01
Solution
public class Solution {
public void ReverseWords(char[] str) {
if(str.Length<2) return;
int i=0, start=0;
reverse(str, 0, str.Length-1);
while(str[i]==' ') { i++;}
while(i<str.Length)
{
start=i;
while(i<str.Length && str[i]!=' ') {i++;}
reverse(str,start, i-1);
i++;
}


}

void reverse(char[] str, int start, int end)
{
while(start<end)
{
var temp = str[start];
str[start] = str[end];
str[end] =temp;
start++;
end--;
}
}
}

Complexity Analysis​

ApproachTimeSpace
SolutionTo be analyzedTo be analyzed