如何使用 C# 逐字反转给定的字符串而不是字母?

创建一个方法 reverse Words,该方法将 char 数组作为输入,并为每个字符反转单词,直到未达到空格为止。在最后一步,将整个字符串从长度 0 反转为 n-1 长度。在第一步中,字符串“这是我的书”将变成“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 = " 这是我的书 ";
         var res = a.reverseWords(s.ToCharArray());
         Console.WriteLine(new String(res));
         Console.ReadLine();
      }
   }
}
输出结果
book my is This

猜你喜欢