LeetCode 刷题【151. 反转字符串中的单词】

151. 反转字符串中的单词

自己做

解:一遍遍历

java 复制代码
class Solution {
    public String reverseWords(String s) {
        String word = "";
        String res = "";
        boolean first_word = true;

        for(int i = 0; i < s.length(); i++){
            char c = s.charAt(i);
            if(c == ' '){
                if(word != ""){
                    if(!first_word){
                        word = word + " ";
                    }
                    res = word + res;
                    first_word = false;
                }
                word = "";
            }
            else
                word += c;
        }

        if(word != ""){
            if(!first_word)
                word = word + " ";
            res = word + res;
        }

        return res;
    }
}

看题解

java 复制代码
class Solution {
    public String reverseWords(String s) {
        // 除去开头和末尾的空白字符
        s = s.trim();
        // 正则匹配连续的空白字符作为分隔符分割
        List<String> wordList = Arrays.asList(s.split("\\s+"));
        Collections.reverse(wordList);
        return String.join(" ", wordList);
    }
}

作者:力扣官方题解
链接:https://leetcode.cn/problems/reverse-words-in-a-string/solutions/194450/fan-zhuan-zi-fu-chuan-li-de-dan-ci-by-leetcode-sol/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
相关推荐
电科_银尘11 分钟前
【大模型算法与工程 15】手写Self-Attention:Q、K、V与缩放点积
算法
郝学胜-神的一滴3 小时前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
秋天的怀念_David3 小时前
算法一千零一夜 · 第三十三夜 · 跳表
java·程序人生·算法
LK_076 小时前
【力扣】142. 环形链表 II |Python
python·leetcode·链表
Pniubi6 小时前
力扣21合并两个有序链表
算法·leetcode·职场和发展
AIgorithmGEEK7 小时前
std::unordered_map 与 std::unordered_set:接口、算法技巧与权衡 (速查)
c++·算法·哈希表·负载因子·桶·unordered_map·unordered_set
文丑颜不良啊7 小时前
LeetCode3341~3360题目解析
java·leetcode
上海潭龙东海科技有限公司8 小时前
智慧堆场动态模型三维实时孪生重构智能管控
大数据·网络·数据库·算法·重构
Rain的Java大神之路10 小时前
把数组本身变成哈希表:原地哈希搞定 LeetCode 41「缺失的第一个正数」
java·后端·leetcode
阿庆_AI研发工程师10 小时前
Stanford CS336 Lecture 10:大语言模型推理与性能优化
算法