【Leetcode】Reverse word in a string

来源:互联网 发布:mac版千牛 编辑:程序博客网 时间:2024/06/06 02:00

【题目】

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.

【题解】

1.遇到空格就跳过,第一个不是空格的元素,位置用pos记录。

2. 即pos之后,继续,只要不是空格,i++

3.当遇到的是第一个单词,即res长度为0时,直接添加,否则,添加“ ”,然后再在前面添加新的单词,达到reverse的效果,res= s.substring(pos,i),+res;注意顺序

4.i-- 因为在检查是否空格那里i++了


注意:substring函数,start是包含的,而end的标是达不到的;

用+重新赋值的好处是可以直接把新的单词调整到最前面,但是这样的做法是不是要耗费的空间比较大。得是单词数目+空格数目。基本是2倍单词数量。


【代码】

public static String solution(String s){String res= "";for(int i=0;i<s.length();i++){if(s.charAt(i)==' ') continue;int pos=i;while(i<s.length()&&s.charAt(i)!=' ') i++;if(res.length()>0) res=" "+res;res=(s.substring(pos,i))+res;i--;}return res;}

【官方题解】

One simple approach is a two-pass solution: First pass to split the string by spaces into an array of words, then second pass to extract the words in reversed order.

We can do better in one-pass. While iterating the string in reverse order, we keep track of a word’s begin and end position. When we are at the beginning of a word, we append it.

public class Solution {    public String reverseWords(String s) {    String[] a=s.trim().split("\\s+");StringBuilder res=new StringBuilder();for(int i=a.length-1;i>=0;i--){if(i==a.length-1)res.append(a[i]);else res.append(" ").append(a[i]);}return res.toString();    }}
\\s+:

splitpublic String[] split(String regex)根据给定的正则表达式的匹配来拆分此字符串。 然后就要明确正则表达式的含义了:\\s表示   空格,回车,换行等空白符,     +号表示一个或多个的意思,所以...


0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 二岁宝宝流鼻涕怎么办 小婴儿有点鼻塞怎么办 宝宝流鼻涕总不好怎么办 孩子鼻炎睡不好怎么办 鼻炎清鼻涕不止怎么办 宝宝持续低烧流鼻涕怎么办 孩子鼻塞不通气怎么办 2月婴儿感冒怎么办 长期流黄鼻涕怎么办 孩子流清水鼻涕怎么办 小孩有点流鼻子怎么办 初生婴儿堵鼻子怎么办? 小孩反复发烧了怎么办 小孩突然发烧了怎么办 40天宝宝鼻塞怎么办 宝宝伤风鼻子不通怎么办 鼻子伤风不通气怎么办 宝宝伤风流鼻子怎么办 十个月婴儿上火怎么办 一个多月宝宝鼻子有鼻屎怎么办 三个月婴儿感冒发烧怎么办 小孩感冒发烧流鼻涕怎么办 小孩感冒发烧反反复复怎么办 宝宝反复发烧39怎么办 一岁婴儿流鼻涕怎么办 四岁宝宝发烧怎么办 小孩流清鼻涕怎么办? 5宝宝光流清鼻涕怎么办 孩子一直流鼻子怎么办 10岁天天流鼻涕怎么办 喉咙痛又痒咳嗽怎么办 60天宝宝流鼻涕怎么办 宝宝流鼻子严重怎么办 鼻炎鼻涕多鼻塞怎么办 夏天老人感冒流鼻涕怎么办 鼻窦炎流清鼻涕怎么办 鼻子有脓鼻涕怎么办 宝宝有脓鼻涕怎么办 小孩脓鼻涕咳嗽怎么办 哺乳期流黄鼻涕怎么办 宝宝鼻塞流脓涕怎么办