leetcode数组557反转字符串中的单词III
作者:互联网
给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。
示例:
输入:"Let's take LeetCode contest"
输出:"s'teL ekat edoCteeL tsetnoc"
思路:
1.将字符串拆分为字符串数组
2.对于每一个字符串数组,将其封装为 StringBuffer 对象,可以调用 reverse() 方法,将字符串反转,然后调用 toString() 方法,将其还原为字符串
3.调用 String.join() ,拼接字符串 String.join()第一个传入的是拼接的方法(以空格连接),第二个传入的是要拼接的元素
class Solution {
public String reverseWords(String s) {
String[] strings = s.split(" ");
for (int i = 0; i < strings.length; i++) {
strings[i] = new StringBuffer(strings[i]).reverse().toString();
}
String result = String.join(" ", strings);
return result;
}
}
标签:join,String,557,leetcode,单词,拼接,字符串,III,strings 来源: https://blog.csdn.net/m0_49190756/article/details/121628433