如果考虑空间和时间的优化的话,当然可以将上面代码里两个字符串交换部分改为异或实现。 例如将 char temp=restr; restr=restr[j]; restr[j]=temp; 改为 restr^=restr[j]; restr[j]^=restr; restr^=restr[j]; |
//"I am a student” => "student a am I"(只适合中间只有一个空格的情况,中间有多个空格的情况后续补上)
static void ReverseWords(char[] sentence)
{
//先将整个句子反转,例如:“I am a student” => "tneduts a ma I"
ReverseString(sentence, 0, sentence.Length-1);
int startIndex = 0, endIndex = 0;
int i = 0;
while( i < sentence.Length)
{
if (sentence[i] == ' ')//Means the end of a word
{
endIndex = i - 1;
ReverseString(sentence, startIndex, endIndex);
if (i + 1 < sentence.Length)
{
startIndex = i + 1;
endIndex = startIndex;
}
}
else
{
endIndex++;
}
i++;
}
}
//反转整个句子
static void ReverseString(char[] str, int startIndex, int endIndex)
{
int len = endIndex - startIndex + 1;
char temp;
for (int i = 0; i < len/2; i++)
{
temp = str[i + startIndex];
str[i + startIndex] = str[startIndex + len - i - 1];
str[startIndex + len - i - 1] = temp;
}
}