文章最前: 我是Octopus,这个名字来源于我的中文名--章鱼;我热爱编程、热爱算法、热爱开源。所有源码在我的个人github ;这博客是记录我学习的点点滴滴,如果您对 Python、Java、AI、算法有兴趣,可以关注我的动态,一起学习,共同进步。
相关文章:
- LeetCode:55. Jump Game(跳远比赛)
- Leetcode:300. Longest Increasing Subsequence(最大增长序列)
- LeetCode:560. Subarray Sum Equals K(找出数组中连续子串和等于k)
文章目录:
题目描述:
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.
Example 1:
Input: "Let's take LeetCode contest"
Output: "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.
java实现方法1:
/**
* 反转字符串
*
* @param s 字符串
* @return 反转字符串
*/
public String reverseWords(String s) {
StringBuffer result = new StringBuffer();
int length = s.length();
int i = 0;
while (i < length) {
int start = i;
while (i < length && s.charAt(i) != ' ') {
i++;
}
for (int p = i - 1; p >= start; p--) {
result.append(s.charAt(p));
}
while (i < length && s.charAt(i) == ' ') {
i++;
result.append(' ');
}
}
return result.toString();
}
时间复杂度:O(n)
空间复杂度:O(n)
Python实现方法1:
def reverse_words(self, s: str) -> str:
'''
单词反转
Args:
arr: 字符串
Returns:
反转后字符串
'''
res = ''
length = len(s)
i = 0
while i < length:
start = i
while i < length and s[i] != ' ':
i += 1
for p in range(start, i)[::-1]:
res += s[p]
while i < length and s[i] == ' ':
i += 1
res += ' '
return res
时间复杂度:O(n)
空间复杂度:O(n)
java实现方法2:
/**
* 反转字符串
*
* @param s 字符串
* @return 反转字符串
*/
public String reverseWords2(String s) {
String[] strings = s.split(" ");
StringBuilder sb = new StringBuilder();
for (String sub : strings) {
sb.append(new StringBuffer(sub).reverse().toString() + " ");
}
return sb.toString().trim();
}
时间复杂度:O(n)
空间复杂度:O(n)
Python实现方法2:
def reverse_words2(self, s: str) -> str:
'''
单词反转
Args:
arr: 字符串
Returns:
反转后字符串
'''
strs = s.split(' ')
res = []
for sub in strs:
res.append(sub[::-1])
return ' '.join(res)
时间复杂度:O(n)
空间复杂度:O(n)