0
点赞
收藏
分享

微信扫一扫

LeetCode 557. Reverse Words in a String III (Java版; Easy)


​​welcome to my blog​​

LeetCode Top Interview Questions 557. Reverse Words in a String III (Java版; Easy)

题目描述

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.

第一次做; 以空格为分隔符分割字符串, 将每个小字符串翻转再拼接起来

class Solution {
public String reverseWords(String s) {
StringBuilder sb = new StringBuilder();
String[] strs = s.split(" ");
for(int i=0; i<strs.length; i++){
sb.append(core(strs[i])).append(" ");
}
return sb.toString().trim();
}
private String core(String str){
StringBuilder sb = new StringBuilder();
for(int i=str.length()-1; i>=0; i--){
sb.append(str.charAt(i));
}
return sb.toString();
}
}

力扣官方题解(https://leetcode-cn.com/problems/reverse-words-in-a-string-iii/solution/fan-zhuan-zi-fu-chuan-zhong-de-dan-ci-iii-by-leetc/) 主要是看看StringBuilder的reverse(), setLength(), insert()方法

LeetCode 557. Reverse Words in a String III (Java版; Easy)_leetcode


举报

相关推荐

0 条评论