char 배열을 입력으로 사용하고 빈 공간에 도달하지 않을 때까지 모든 문자에 대해 단어를 반대로 하는 방법을 반대로 작성합니다. 마지막 단계에서 전체 문자열을 길이 0에서 n-1 길이로 뒤집습니다. 첫 번째 단계에서 문자열 "This is my book"은 "koob ym si siht"로 바뀝니다. 두 번째 단계가 끝나면 문자열 단어가 "book my is This"로 바뀝니다.
시간 복잡도 - O(N)
예
using System;
namespace ConsoleApplication{
public class Arrays{
static void reverse(char[] str, int start, int end){
char temp;
while (start <= end){
temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
public char[] reverseWords(char[] s){
int start = 0;
for (int end = 0; end < s.Length; end++){
if (s[end] == ' '){
reverse(s, start, end);
start = end + 1;
}
}
reverse(s, 0, s.Length - 1);
return s;
}
}
class Program{
static void Main(string[] args){
Arrays a = new Arrays();
string s = " This is my book ";
var res = a.reverseWords(s.ToCharArray());
Console.WriteLine(new String(res));
Console.ReadLine();
}
}
} 출력
book my is This