Welcome to Subscribe On Youtube

557. Reverse Words in a String III

Description

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

 

Example 1:

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

Example 2:

Input: s = "Mr Ding"
Output: "rM gniD"

 

Constraints:

  • 1 <= s.length <= 5 * 104
  • s contains printable ASCII characters.
  • s does not contain any leading or trailing spaces.
  • There is at least one word in s.
  • All the words in s are separated by a single space.

Solutions

  • class Solution {
        public String reverseWords(String s) {
            StringBuilder res = new StringBuilder();
            for (String t : s.split(" ")) {
                for (int i = t.length() - 1; i >= 0; --i) {
                    res.append(t.charAt(i));
                }
                res.append(" ");
            }
            return res.substring(0, res.length() - 1);
        }
    }
    
  • class Solution {
    public:
        string reverseWords(string s) {
            for (int i = 0, n = s.size(); i < n; ++i) {
                int j = i;
                while (++j < n && s[j] != ' ')
                    ;
                reverse(s.begin() + i, s.begin() + j);
                i = j;
            }
            return s;
        }
    };
    
  • class Solution:
        def reverseWords(self, s: str) -> str:
            return ' '.join([t[::-1] for t in s.split(' ')])
    
    
  • func reverseWords(s string) string {
    	t := []byte(s)
    	for i := 0; i < len(t); i++ {
    		j := i
    		for j < len(t) && t[j] != ' ' {
    			j++
    		}
    		for st, ed := i, j-1; st < ed; st, ed = st+1, ed-1 {
    			t[st], t[ed] = t[ed], t[st]
    		}
    		i = j
    	}
    	return string(t)
    }
    
  • function reverseWords(s: string): string {
        return s
            .split(/\s+/)
            .map(str => {
                let res = '';
                for (const c of str) {
                    res = c + res;
                }
                return res;
            })
            .join(' ');
    }
    
    
  • class Solution {
        /**
         * @param String $s
         * @return String
         */
        function reverseWords($s) {
            $sArr = explode(' ', $s);
            for ($i = 0; $i < count($sArr); $i++) {
                $sArr[$i] = strrev($sArr[$i]);
            }
            return implode(' ', $sArr);
        }
    }
    
  • impl Solution {
        pub fn reverse_words(s: String) -> String {
            s.split(' ')
                .map(|s| s.chars().rev().collect::<String>())
                .collect::<Vec<_>>()
                .join(" ")
        }
    }
    
    

All Problems

All Solutions