LeetCode - 557. Reverse Words in a String III(String, Two Pointers)


質問する
文字列sが指定されている場合、スペースと初期単語の順序を保持しながら、文内の各単語の文字順序を反転します.
Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
https://leetcode.com/problems/reverse-words-in-a-string-iii/
Example 1:
Input: s = "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Example 2:
Input: s = "God Ding"
Output: "doG gniD"
に答える
これはJavaです.
  • charat()を使用してスペースを検索します.
  • StringBuilderのappend()加算を使用して、String reverse()を使用して単語の順序を反転します.
  • class Solution {
        public String reverseWords(String s) {
            StringBuilder res = new StringBuilder("");
            int i=0;
            for(int j = 1;j<s.length();j++){
                if(s.charAt(j)==' '){
                    res.append(new StringBuilder(s.substring(i,j)).reverse()+" ");
                    i=j+1;   
                }      
            }
            res.append(new StringBuilder(s.substring(i)).reverse());
            return res.toString();
        }
    }