当前位置:网站首页>LeetCode Daily 2 Questions 02: Reverse the words in a string (1200 each)

LeetCode Daily 2 Questions 02: Reverse the words in a string (1200 each)

2022-08-10 22:34:00 The man fishing alone like snow.

题目如下:

在这里插入图片描述
解题思路:运用两个StringBuilder,One to carry the reversed string One is to record reverse words
Use characters to determinecwhen including spaces Then add the data of the reversed word to the first carrying the reversed string and add spaces,然后newA new function that adds reversed strings.最后return返回结果

class Solution {
    
    public String reverseWords(String s) {
    
        StringBuilder sb1 = new StringBuilder();
        StringBuilder sb2 = new StringBuilder();
        int len = s.length();//Reduce consumed memory
        for (int i = 0; i < len; i++) {
    
            char c = s.charAt(i);
            if (c == ' ') {
    
                sb1.append(sb2.reverse());
                sb1.append(' ');
                sb2 = new StringBuilder();
            } else {
    
                sb2.append(c);
            }
        }
        sb1.append(sb2.reverse());
        return sb1.toString();//返回结果
    }
}

在这里插入图片描述

原网站

版权声明
本文为[The man fishing alone like snow.]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/222/202208102151155786.html