LeetCode(557)——Reverse Words in a String III

題目:

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:

Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

Note: In the string, each word is separated by single space and there will not be any extra space in the string.

 

AC:

public String reverseWords(String s) {
        if (s == null || s.length() < 2) {
            return s;
        }
        
        int begin = 0;
        int end = 0;

        char[] words = s.toCharArray();
        int index = s.indexOf(' ');
        
        while (index > 0) {
            reverseWord(words, begin, index - 1);

            begin = index + 1;
            
            index = s.indexOf(' ', begin);
        }
        
        
        reverseWord(words, begin, s.length() - 1);
        
        return String.valueOf(words);

    }
    
    
    private void reverseWord(char[] words, int begin, int end) {
        while (end > begin) {
            char tmp = words[end];
            words[end] = words[begin];
            words[begin] = tmp;
            
            end--;
            begin++;
        }
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章