题目
给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。
示例 :
输入: "Let's take LeetCode contest"
输出: "s'teL ekat edoCteeL tsetnoc"
注意 :在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。
算法实现
public string ReverseWords(string s)//调用之前的函数
{
if (s == "")
return "";
string res = null;
int head;
for (int i = 0; i < s.Length; i++)
{
head = i;
while (i < s.Length&&s[i] != ' ' ) { i++; }
char[] temp = s.Substring(head, i - head).ToArray();
ReverseString(temp);
res = res + string.Join("",temp)+" ";
}
return res.Substring(0,s.Length);
}
public void ReverseString(char[] s)//交换不用额外空间
{
int end = s.Length;
int half = end / 2;
end = end - 1;
for (int i = 0; i < half; ++i, --end)
{
s[i] = (char)(s[i] ^ s[end]);
s[end] = (char)(s[end] ^ s[i]);
s[i] = (char)(s[i] ^ s[end]);
}
}
执行结果
执行结果 : 通过
执行用时 : 236 ms, 在所有 C# 提交中击败了34.12%的用户
内存消耗 : 41.9 MB, 在所有 C# 提交中击败了8.00%的用户
小的总结
本次题目第一想到的是对之前的函数进行调用,然后对主体函数进行编写来适应调用函数的输入,但是效率不太高。之后看到一个解题区的大佬点醒了我,应该同时更改之前的函数来适应本道题目,而不是一味的编写主函数去适应之前的函数,这样能省很多事并且效率也能提高。
总而言之,看到题目想到之前做过的函数是好事,但是要把以前编写的函数针对本题加以改动,这样才能写出灵活简单的代码。
更改后的代码
public string ReverseWords(string s)
{
StringBuilder a = new StringBuilder(s);
int front = 0;
for (int i = 0; i < s.Length; i++)
{
if (s[i] == ' ')
{
ReverseString(front, i - 1, a);
front = i + 1;
}
}
ReverseString(front, s.Length - 1, a);
return a.ToString();
}
public void ReverseString(int front, int tail, StringBuilder str)
{
while (front < tail)
{
str[front] ^= str[tail];
str[tail] ^= str[front];
str[front++] ^= str[tail--];
}
}