タイトル説明
文章中の単語の順番が、そのまま単語の文字の順序を逆に、英語の文を入力します。シンプルさ、句読点や治療などの一般的な手紙のために。例えば、入力文字列が「私は学生です。」、出力「学生。Aは、私は」。
アイデア解析
まず、文字列全体が反転して、単一の単語にひっくり返さ
テストケース
- 機能テスト:複数の単語が文中にある、文章中の1つの単語だけ。
- 特別なテスト入力:文字列ポインタは、ポインタnullptrであり、コンテンツ文字列が空である、
文字列だけのスペース。
Javaコード
public class Offer058_01 {
public static void main(String[] args) {
test1();
test2();
test3();
}
public static String ReverseSentence(String str) {
return Solution1(str);
}
private static String Solution1(String str) {
if(str==null || str.length() <= 0) {
return str;
}
char[] chars = str.toCharArray();
reverseCore(chars, 0, chars.length-1);
int start = 0;
int end =0;
while(start<chars.length){
while(end<chars.length && chars[end]!=' ')
end++;
reverseCore(chars,start,end-1);
start=++end;
}
return String.valueOf(chars);
}
private static void reverseCore(char[] chars ,int start,int end) {
while(start<end) {
char tmp = chars[start];
chars[start]=chars[end];
chars[end]=tmp;
start++;
end--;
}
}
private static void test1() {
}
private static void test2() {
}
private static void test3() {
}
}