-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReverse Words in a String II Solution
51 lines (42 loc) · 1.1 KB
/
Reverse Words in a String II Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
Given an input string , reverse the string word by word.
Example:
Input: ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
Output: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]
Note:
A word is defined as a sequence of non-space characters.
The input string does not contain leading or trailing spaces.
The words are always separated by a single space.
Follow up: Could you do it in-place without allocating extra space?
Solution :
public class Solution {
//the sky is blue
//eht yks si eulb
public void ReverseWords(char[] s) {
if(s==null||s.Length==1)
return;
int i=0;
int j=0;
while(i<s.Length-1)
{
if(s[i]==' ')
{
reverse(s,j,i-1);
j=i+1;
}
i++;
}
reverse (s,j,s.Length-1);
reverse(s,0,s.Length-1);
}
public void reverse(char[] s, int i,int j)
{
while(i<j)
{
var temp=s[i];
s[i]=s[j];
s[j]=temp;
i++;
j--;
}
}
}