Java solution. O(N) solution


  • 0
    Q

    public String reverseWords(String s) {
    //First parse all the words into a String arraylist. Then scan from right to left to create the new string. pay attention to insert single space to the result string
    if (s == null || s.length() == 0) {
    return "";
    }
    List<String> list = new ArrayList<String>();
    int end = 0;
    int start = 0;
    while (end < s.length()) {
    while (end < s.length() && s.charAt(end) == ' ') {
    end++;
    }
    if (end >= s.length()) {
    break;
    }
    start = end;
    while (end < s.length() && s.charAt(end) != ' ') {
    end++;
    }
    list.add(s.substring(start, end));
    }
    StringBuilder sb = new StringBuilder();
    for (int i = list.size() - 1; i >= 1; i--) {
    sb.append(list.get(i));
    sb.append(' ');
    }
    if (list.size() > 0) {
    sb.append(list.get(0));
    }

        return sb.toString();
    }>! ![Spoiler''](image url)'

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.