LeetCode之Reverse Words in a String

1.(原文)问题描述

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Given an input string, reverse the string word by word.
 
For example,
Given s = "the sky is blue" ,
return   "blue is sky the" .
 
click to show clarification.
 
Clarification:
What constitutes a word?
A sequence of non-space characters constitutes a word.
Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces.
How about multiple spaces between two words?
Reduce them to a single space in the reversed string.

 2.问题翻译

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
对于一个输入的字符串,逐个词反转这个字符串
 
例如,
 
所给的字符串s =  "the sky is blue" ,
返回 "blue is sky the" .
 
 
说明:
 
  每个词由什么组成?
 
    由不含空格字符的序列组成每个词
 
  输入的字符串的开头或者结尾能否包含空格?
    
    是的,当然可以。但是在你反转的时候你应该把开头和结尾的字符空格去掉。
 
如果两个词之间含有多个空格呢?
 
  在反转后的字符串中应该讲他们减少为一个空格。
    
 
     

 3.思路分析

  很显然在拿到字符串的时候首先先进行判断是否为空,如果为空应该原样输出;如果不为空则首先需要处理的情况就是考虑到字符串中每个词之间存在多个空格的情况,

我们需要将这些空格首先变成一个,最后开始处理这个字符串。通过获取字符串数组然后反向输出,在输出的时候拼接空格得到反转后的数组

4.实现过程

Solution.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package   ReverseWords;
 
public   class   Solution {
     
     public   String reverseWords(String s) {
         
         if (s == null || "" .equals(s)){ //判断是否为空,为空则直接返回
             return   "" ;
         }
         StringBuffer strBuffer = new   StringBuffer();
         String []tempArray = s.replaceAll( "\\s{1,}" , " " ).split( " " ); //去除多空格情况然后返回字符数组
         for ( int   index = tempArray.length- 1 ;index >= 0 ;index--){
             strBuffer.append(tempArray[index]+ " " ); //拼接反转数组
         }
         return   strBuffer.toString().trim();
     }
}

  SolutionTest.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package   ReverseWords;
 
public   class   SolutionTest {
 
     /**
      * @param args
      */
     public   static   void   main(String[] args) {
         // TODO Auto-generated method stub
         String str = "   a   b " ;
         System.out.println( "反转后的字符串是:" + new   Solution().reverseWords(str));
     }
 
}

 5.感觉考察的东西不多,主要在于细节字符串中空格的处理还有就是字符串相关函数的应用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值