why it is not sb.substring(0,s.length() - 1) but sb.substring(0,s.length)? I think I should discard the last space...


  • 0

    '''public class Solution {
    public String reverseWords(String s) {
    if(s == null) return ""; // null string, return null
    else if(s.indexOf(' ') == -1) return reverse(s); // only one word, return reverse(s)
    else { // at least one space
    String[] array = s.split(" "); // split words into string array elements
    StringBuilder sb = new StringBuilder();
    for(String word : array) {
    sb.append(reverse(word)).append(" ");
    }
    return sb.substring(0,s.length());
    }
    }

    private String reverse(String element) {
        if(element == null || element.length() == 0) return ""; // null string, return null
        if(element.length() == 1) return element; // only one char, return itself
        char[] arr = element.toCharArray(); // convert into char array, and do the swap operation
        int left = 0;
        int right = arr.length - 1;
        for(left = 0; left < right; left++, right--) {
            char temp = arr[left];
            arr[left] = arr[right];
            arr[right] = temp;
        }
        return String.valueOf(arr); // convert array back to string type
    }
    

    }'''


  • 0
    N

    @shilinpuerduo

    The substring method for String Builder is [inclusive,exclusive). If you do [0,s.length-1), you are actually doing [0,s.length-2] and cutting off the last character in your answer.


Log in to reply
 

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