Reverse Words in a String

本文详细解析了LeetCode上的一道经典题目——字符串单词翻转问题。通过Java实现,介绍了如何逐词翻转输入字符串中的单词顺序,并确保输出结果符合规范:去除多余的空格并合并多个连续空格为单个空格。

https://leetcode.com/problems/reverse-words-in-a-string/

Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".

Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.

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.

 

 1 import java.util.ArrayList;
 2 import java.util.List;
 3 import java.util.Stack;
 4 
 5 public class Solution {
 6     public static String reverseWords(String s) {
 7     List<String> li=new ArrayList();
 8         int len0=s.length();
 9         int len1=0;
10         String x="";
11         for(int i=0;i<len0;i++){
12             char c=s.charAt(i);
13             if(c!=' ') x+=c;
14             else{
15             if(x.length()!=0){
16                 len1++;
17                 li.add(x);
18             }
19             x="";
20             }
21         }
22         if(x.length()!=0) li.add(x);
23         Stack<String>st=new Stack();
24         for(String str:li){
25             st.add(str);
26         }
27         s="";
28         while(!st.isEmpty()){
29             s+=st.pop();
30             if(st.size()!=0)
31             s+=" ";
32         }
33         return s;
34     }
35     public static void main(String[]args){
36     System.out.println(reverseWords("   a   b "));
37     }
38 }

 

转载于:https://www.cnblogs.com/qq1029579233/p/4485731.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值