剣指offer:単語の順序を反転(java)
1595 ワード
/**
* :
* Fish, , 。
* Cat Fish , Fish , 。 ,“student. a am I”。
* , , “I am a student.”。
* Cat , ?
*
* :
* , 。
*/
public class P284_ReverseSentence {
public String ReverseSentence(String str){
String result = "";
if (str == null) {
return result;
}
int start = 0;
int end = str.length() - 1;
String temp = ReverseWords(str,start,end);
char[] array = temp.toCharArray();
for (int i = 0; i < array.length; i++) {
int low = i;
while (i < array.length && array[i] != ' ') {
i++;
}
int high = i - 1;
temp = ReverseWords(temp, low, high);
}
result = temp;
return result;
}
public String ReverseWords(String str, int start, int end) {
char[] array = str.toCharArray();
while (start < end) {
char temp = array[start];
array[start] = array[end];
array[end] = temp;
start++;
end--;
}
String result = new String(array);
return result;
}
public static void main(String[] args) {
String str = "I am a student.";
P284_ReverseSentence test = new P284_ReverseSentence();
String result = test.ReverseSentence(str);
System.out.println(result);
}
}