当前位置:网站首页>[daily training -- Tencent selected 50] 557 Reverse word III in string

[daily training -- Tencent selected 50] 557 Reverse word III in string

2022-07-05 08:37:00 Puppet__

subject

Given a string s , You need to reverse the character order of each word in the string , Keep the initial order of spaces and words .

Example 1:
Input :s = “Let’s take LeetCode contest”
Output :“s’teL ekat edoCteeL tsetnoc”

Example 2:
Input : s = “God Ding”
Output :“doG gniD”

Tips :
1 <= s.length <= 5 * 104
s Include printable ASCII character .
s Does not contain any beginning or ending spaces .
s in At least There's a word .
s All words in the are separated by a space

Code

package tencent50;

public class leetcode557 {
    
    //  Use extra space , And through the spaces in the original string, it will be divided into multiple segments , Flip each segment 
    public String reverseWords(String s) {
    
        StringBuffer  sb = new StringBuffer();
        int len = s.length();
        int i = 0;

        while( i < len){
    
            int start = i;
            //  First find out where the blank is 
            while (i < len && s.charAt(i) != ' '){
    
                i++;
            }
            //  Flip word 
            for (int j = i - 1; j >= start; j--){
    
                sb.append(s.charAt(j));
            }
            // Skip spaces after 
            while (i < len && s.charAt(i) == ' '){
    
                i++;
                sb.append(' ');
            }
        }
        return sb.toString();
    }

    public static void main(String[] args) {
    
        leetcode557 obj = new leetcode557();
        System.out.println(obj.reverseWords("Let's take LeetCode contest"));
    }
}

原网站

版权声明
本文为[Puppet__]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207050835595609.html