4月打卡活动第10天 LeetCode第151题:翻转字符串里的单词(中等)
题目:给定一个字符串,逐个翻转字符串中的每个单词。 解题思路:最直接的做法。
class Solution {
public String reverseWords ( String s) {
String ans = "" ;
int len = s. length ( ) ;
int j = len- 1 ;
int i = j;
while ( i>= 0 && s. charAt ( i) == ' ' ) {
i-- ;
}
j= i;
while ( j>= 0 ) {
while ( i>= 0 && s. charAt ( i) != ' ' ) {
i-- ;
}
if ( ans!= "" ) ans += " " ;
for ( int k= i+ 1 ; k<= j; k++ ) {
ans += s. charAt ( k) ;
}
while ( i>= 0 && s. charAt ( i) == ' ' ) {
i-- ;
}
j= i;
}
return ans;
}
}
class Solution {
public String reverseWords ( String s) {
s = s. trim ( ) ;
List< String> wordList = Arrays. asList ( s. split ( "\\s+" ) ) ;
Collections. reverse ( wordList) ;
return String. join ( " " , wordList) ;
}
}
作者:LeetCode- Solution
链接:https: / / leetcode- cn. com/ problems/ reverse- words- in- a- string/ solution/ fan- zhuan- zi- fu- chuan- li- de- dan- ci- by- leetcode- sol/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。