如何使用 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
廣告