共计 1297 个字符,预计需要花费 4 分钟才能阅读完成。
公众号:爱写 bug(ID:icodebugs)
给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
示例 1:
输入: "Let's take LeetCode contest"输出:"s'teL ekat edoCteeL tsetnoc"
注意: 在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。
Note: In the string, each word is separated by single space and there will not be any extra space in the string.
解题思路:
每次遇到空格字符,就把 从上一次空格字符开始到该空格字符止之间的所有字符反转一下即可,只需要注意最后一个字符结束时,并不是空格字符,要再加一个判断是否是已经索引到最后一位。
'abc def' 原字符串 | |
['a' , 'b' , 'c' , '' ,'d','e','f'] 转成 char[] 型数组 | |
['c' , 'b' , 'a' , ' '...] 遍历数组,遇到第一个空格,把该空格到上个空格之间的字母反转 | |
[... '' ,'d','e','f'] 遍历到最后一位,不是空格,依然要反转到前一个空格间的字母 | |
[... '' ,'f','d','e'] 反转'cba fde' 转成字符串输出 |
Java:
class Solution {public String reverseWords(String s) {int sLen = s.length(), k = 0, j = 0;// j 记录空格字符前的索引位置 | |
char strs[] = s.toCharArray(), temp;// 转为字符数组 | |
for (int i = 0; i < sLen; i++) {if (strs[i] == ' ') j = i - 1;// 遇到空格字符 j 值减 1,为截取的字母段的最后一个字母的索引 | |
else if (i == sLen - 1) j = i;// 如果到最后一位,则 j 值不应该再减 1 | |
else continue; | |
for (; j >= k; j--, k++) {// 交换位置 | |
temp = strs[j]; | |
strs[j] = strs[k]; | |
strs[k] = temp; | |
} | |
k = i + 1;// k 记录空格字符后的索引位置 | |
} | |
return String.valueOf(strs); | |
} | |
} |
python 不再复现上述定义指针解题的思路,这里再次投机取巧,利用 python 切片特性及 split()
、join()
函数解题,解题思路:
'abc def gh' 原字符串 | |
'hg fed cba' 切片特性反转字符串 | |
['hg' , 'fed' , 'cba'] split() 分割字符串 | |
['cba' , 'fed' , 'hg'] 切片反转数组 | |
'cba fed hg' 拼接成字符串 |
Python3:
class Solution: | |
def reverseWords(self, s: str) -> str: | |
return ' '.join(s[::-1].split()[::-1]) |
正文完