557. Reverse Words in a String III
# Easy
string can't be modified but can use index
[::-1] is to reverse a list
class Solution:
def reverseWords(self, s: str) -> str:
if len(s) <= 1:
return s
l = s.split()
s = ''
for i in l:
s = s + i[::-1] + ' '
return s[:-1]// Some code
class Solution {
public String reverseWords(String s) {
String[] words = s.split(" ");
StringBuilder res = new StringBuilder();
for(String word: words) {
StringBuilder re_word = new StringBuilder(word);
res.append(re_word.reverse().toString() + " ");
}
return res.toString().trim();
}
}Last updated
Was this helpful?