Reversing characters in each word in a sentence - Stack Implementation

前端 未结 6 1427
情深已故
情深已故 2020-12-22 06:02

This code is inside the main function:

Scanner input = new Scanner(System.in);

System.out.println(\"Type a sentence\");
String sentence = input         


        
6条回答
  •  抹茶落季
    2020-12-22 06:13

    public class reverseStr {
    public static void main(String[] args) {
        String testsa[] = { "", " ", "       ", "a ", " a", " aa bd  cs " };
        for (String tests : testsa) {
            System.out.println(tests + "|" + reverseWords2(tests) + "|");
        }
    }
    
    public static String reverseWords2(String s) {
        String[] sa;
        String out = "";
        sa = s.split(" ");
        for (int i = 0; i < sa.length; i++) {
            String word = sa[sa.length - 1 - i];
            // exclude "" in splited array
            if (!word.equals("")) {
                //add space between two words
                out += word + " ";
            }
        }
        //exclude the last space and return when string is void
        int n = out.length();
        if (n > 0) {
            return out.substring(0, out.length() - 1);
        } else {
            return "";
        }
    }
    

    }

    This can pass in leetcode

提交回复
热议问题