LeetCode 151:给定一个字符串,逐个翻转字符串中的每个单词 Reverse Words in a String

简介: 公众号:爱写bug(ID:icodebugs)翻转字符串里的单词Given an input string, reverse the string word by word.示例 1:输入: "the sky is blue"输出: "blue is sky the"示例 2:输入: " hello world! "输出: "world! hello"解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。

公众号:爱写bug(ID:icodebugs)

翻转字符串里的单词

Given an input string, reverse the string word by word.

示例 1:

输入: "the sky is blue"
输出: "blue is sky the"

示例 2:

输入: "  hello world!  "
输出: "world! hello"
解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。

示例 3:

输入: "a good   example"
输出: "example good a"
解释: 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。

说明:

  • 无空格字符构成一个单词。
  • 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
  • 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。

进阶:

请选用 C 语言的用户尝试使用 O(1) 额外空间复杂度的原地解法。

Note:

  • A word is defined as a sequence of non-space characters.
  • Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
  • You need to reduce multiple spaces between two words to a single space in the reversed string.

Follow up:

For C programmers, try to solve it in-place in O(1) extra space.

解题思路:

Java 字符串不支持运算符重载,无法用原地解法。 我们将字符串转为字符型数组并用两个指针来解这道题。指针 i 作为原字符串转为字符数组的索引,从右向左移。指针 j 作为新字符数组索引,从左向右赋值得到原数组 count 长度的字符。count记录遇到的字母数量,每次遇到 空格 字符,新数组得到从该空格字符 向右 count 个字符并刷新count 计数。

Java:

class Solution {
    public String reverseWords(String s) {
        if (s.length()==0)return s;//如果为空直接返回
        char strs[]=s.toCharArray(),ans[]=new char[s.length()];//字符串转为char字符数组
        int count=0,j=0;//全局变量j记录新数组索引
        for(int i=s.length()-1;i>=0;i--){指针i从右向左遍历strs字符
            if(strs[i]==' '){//判断是否为空格字符
                int k=i+1;
                if(count>0){
                    while (--count>=0){//从字符i向右count个字符赋给新数组ans
                        ans[j++]=strs[k++];
                    }
                    ans[j++]=' ';
                    count=0;//count初始化为0
                }
            }else if(i==0){
                for(;i<=count;i++)ans[j++]=strs[i];//左移到第一个字符时证明不是以空格开头,则从0获取count+1个个字符赋给ans
                j+=1;
                break;
            }
            else {
                count++;//如果是字母,则count累加1
            }
        }
        if(j<1)return "";//如果j依然是0,则原字符串全为空格,返回空字符串
        String string=String.valueOf(ans,0,j-1);//char数组转为字符串返回
        return string;
    }
}

为了考虑性能,转成了多个判断,所以有些繁琐。最终运行:Your runtime beats 99.91 % of java submissions

Python3:

python完全可以实现Java的思路,不再复现。这里利用函数投机取巧:

split() ,它可以把传入字符串剔除空格后返回 所有单词的数组

join() ,它可以指定一个数组以特定字符为间隔,拼接成一个字符串

加上 [::-1] 反转数组,一行代码既可实现该题目要求

' abc def ' 原字符串

['abc' , 'def'] 剔除空格返回String型单词数组

['def' , 'abc'] 切片反转数组

'def abc' 拼接成字符串

class Solution:
    def reverseWords(self, s: str) -> str:
        return " ".join(s.split()[::-1]) # 剔除所有空格字符返回数组并反转,以空格为间隔把数组拼成字符串
目录
相关文章
|
4月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
361 100
|
4月前
|
开发者 Python
Python中的f-string:高效字符串格式化的利器
Python中的f-string:高效字符串格式化的利器
491 99
|
4月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
|
4月前
|
开发者 Python
Python f-string:高效字符串格式化的艺术
Python f-string:高效字符串格式化的艺术
|
5月前
|
Python
Python中的f-string:更简洁的字符串格式化
Python中的f-string:更简洁的字符串格式化
327 92
|
6月前
|
自然语言处理 Java Apache
在Java中将String字符串转换为算术表达式并计算
具体的实现逻辑需要填写在 `Tokenizer`和 `ExpressionParser`类中,这里只提供了大概的框架。在实际实现时 `Tokenizer`应该提供分词逻辑,把输入的字符串转换成Token序列。而 `ExpressionParser`应当通过递归下降的方式依次解析
384 14
|
Unix Shell Linux
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
本文提供了几个Linux shell脚本编程问题的解决方案,包括转置文件内容、统计词频、验证有效电话号码和提取文件的第十行,每个问题都给出了至少一种实现方法。
291 6
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
|
Python
【Leetcode刷题Python】剑指 Offer 32 - III. 从上到下打印二叉树 III
本文介绍了两种Python实现方法,用于按照之字形顺序打印二叉树的层次遍历结果,实现了在奇数层正序、偶数层反序打印节点的功能。
183 6
|
搜索推荐 索引 Python
【Leetcode刷题Python】牛客. 数组中未出现的最小正整数
本文介绍了牛客网题目"数组中未出现的最小正整数"的解法,提供了一种满足O(n)时间复杂度和O(1)空间复杂度要求的原地排序算法,并给出了Python实现代码。
394 2