New Ket recently had a new employee fish, who always held an English magazine every morning and wrote some sentences in the book. Colleague Cat was interested in what Fish had written, and one day he borrowed it from fish to read it, but he couldn't understand what it meant. For example, "student." A am I ". It was later realized that the guy had flipped the order of the words in the sentence and the correct sentence would be "I am a student." Cat is not good at one by one flipping these words, can you help him.
Ideas:
(1) Flip the whole sentence first
(2) Flip each word again
When you flip each word, use two variables to control, start is the beginning of the word, end is the space after the word, each flip character interval between the start~end-1
Note: The last word is not a space
public string reversesentence (String str)
{
if (str = NULL | | Str.length () <2)
{return
str;
}
char[] array = Str.tochararray ();
Reserve (ARRAY,0,ARRAY.LENGTH-1);
int start = 0;//records the starting position of each word
int end = 0;//Word's ending position while
(ends < Array.Length)
{
if (array[end)!= ')
{
if (end = = array.length-1)//The last word has no space
{
reserve (array,start,end);
}
end++;
}
else if (array[end]== ')///When a space is encountered, flip the word before the space and set the start to end
{
reserve (array,start,end-1);
end++;
Start = end;//The starting position of the next word
} return
string.valueof (array)
;
private void Reserve (char[] array,int start,int end)
{
char temp = ';
while (Start < end)
{
temp = Array[start];
array[start++] = Array[end];
array[end--] = temp;
}
}