不用额外字符串存储空间将句子中的每个单词倒叙
public static string Reverse(char[] inputString) { int left = 0; int right = -1; int currentIndex = 0; if (inputString.Length <= 0) throw new ArgumentNullException("inputString", "input null exception occured"); for (; currentIndex < inputString.Length; currentIndex++) { if (inputString[currentIndex] != ' ') { right++; } while (((inputString[currentIndex] == ' '|| inputString.Length - 1 == currentIndex) && left <= right)) { Swap(ref inputString[left++], ref inputString[right--]); } if (inputString[currentIndex] == ' ') { left = currentIndex + 1; right = currentIndex; } } return inputString.ToString(); } public static void Swap(ref char a, ref char b) { char temp = a; a = b; b = temp; }
今天写了一下。感觉还有待优化。先贴出来。