最近我在一次讨论中被要求编写一个算法来实现一个句子的单词反转(不是整个句子的反转),而不使用除 ToCharArray 和 Length 之外的 Split/Replace/Reverse/Join 等字符串操作。以下是我可以在 5 分钟内设计的内容。尽管该算法运行良好,但它的实现方式似乎有点难看。有人可以通过完善代码来帮助我吗?
string ReverseWords(string s)
{
string reverseString = string.Empty;
string word = string.Empty;
var chars = s.ToCharArray();
List<ArrayList> words = new List<ArrayList>();
ArrayList addedChars = new ArrayList();
Char[] reversedChars = new Char[chars.Length];
int i = 1;
foreach (char c in chars)
{
if (c != ' ')
{
addedChars.Add(c);
}
else
{
words.Add(new ArrayList(addedChars));
addedChars.Clear();
}
if (i == s.Length)
{
words.Add(new ArrayList(addedChars));
addedChars.Clear();
}
i++;
}
foreach (ArrayList a in words)
{
for (int counter = a.Count - 1; counter >= 0; counter--)
{
reverseString += a[counter];
}
if(reverseString.Length < s.Length)
reverseString += " ";
}
return reverseString;
}