Sword refers to offer-58. Reversing the word order column-analysis and code [Java]
1. Title
Niuke recently came to Fish, a new employee. He always took an English magazine every morning and wrote some sentences in his notebook. My colleague Cat was very interested in what Fish wrote. One day he borrowed it from Fish to read it, but couldn't read it. For example, "student. a am I". Later I realized that this guy had reversed the order of the words in the sentence. The correct sentence should be "I am a student." Cat is not good at flipping these words one by one. Can you help him?
Two, analysis and code
1. Two flips
(1) Thinking
First flip each word, and then flip the entire sentence twice to achieve the goal.
(2) Code
public class Solution {
public String ReverseSentence(String str) {
if (str.trim().equals(""))
return str;
char[] chstr = str.toCharArray();
int l = 0, length = str.length();
for (int i = 0; i < length; i++) {
if (chstr[i] == ' ') {
Reverse(chstr, l, i - 1);
l = i + 1;
}
if (i == length - 1 && l < i)
Reverse(chstr, l, length - 1);
}
Reverse(chstr, 0, length - 1);
return String.valueOf(chstr);
}
public void Reverse(char[] chstr, int l, int r) {
int m = (l + r) >> 1;
for (int i = l; i <= m; i++) {
char temp = chstr[i];
chstr[i] = chstr[l + r - i];
chstr[l + r - i] = temp;
}
return;
}
}
(3) Results
Running time: 21ms, occupied memory: 9648k.
2. Direct splicing
(1) Thinking
If the auxiliary space is allowed, just splice the original string directly.
(2) Code
public class Solution {
public String ReverseSentence(String str) {
if (str.trim().equals(""))
return str;
String[] substr = str.split(" ");
String ans = substr[substr.length - 1];
for (int i = substr.length - 2; i >= 0; i--)
ans = ans.concat(" " + substr[i]);
return ans;
}
}
(3) Results
Running time: 20ms, occupied memory: 9360k.
Three, other
Nothing.