如何使用 C# 反转一个给定字符串中的单词,而不是字母?
创建一个接收字符数组作为输入的 reverse Word 方法,对于每一个字符,在未到达空格之前,反转单词。在最后一步中,从长度 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP