Reverse a given sentence in Java

前端 未结 14 1896
别跟我提以往
别跟我提以往 2020-11-27 04:52

Can anyone tell me how to write a Java program to reverse a given sentence?

For example, if the input is:

\"This is an interview question\"

14条回答
  •  执笔经年
    2020-11-27 05:22

    Just being different: a recursive solution. Doesn't add any extra spaces.

    public static String reverse(String s) {
       int k = s.indexOf(" ");
       return k == -1 ? s : reverse(s.substring(k + 1)) + " " + s.substring(0, k);
    }
    
    
    System.out.println("[" + reverse("This is interview question") + "]");
    // prints "[question interview is This]"
    

    I will also improve on the split solution by using \b instead (it's so obvious!).

        String[] parts = "Word boundary is better than space".split("\\b");
        StringBuilder sb = new StringBuilder();
        for (int i = parts.length; i --> 0 ;) {
            sb.append(parts[i]);
        }
        System.out.println("[" + sb.toString() + "]");
        // prints "[space than better is boundary Word]"
    

提交回复
热议问题