Reverse Words in a String [Medium]
来源:互联网 发布:怎样查看udp端口 编辑:程序博客网 时间:2024/05/02 21:26
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.
===================================================Answer ==================================================
public class Solution { public String reverseWords(String s) { if(s==null) return null; if(s.trim().length()==0) return s.trim(); s=s.trim(); String[] tempArr = new String[s.length()]; StringBuilder sb = new StringBuilder(); char[] charArr = s.toCharArray(); int tempArrIndex= 0; for(int i=0;i<charArr.length;i++) { char c=charArr[i]; if(c!=' ') { sb.append(c); if(i==charArr.length-1){ tempArr[tempArrIndex]=sb.toString(); sb.setLength(0); tempArrIndex++; } } else if(c==' '&& sb.length()>0) { tempArr[tempArrIndex]=sb.toString(); sb.setLength(0); tempArrIndex++; continue; } } for(int i=tempArrIndex-1;i>=0;i--) { sb.append(tempArr[i]).append(' '); } return sb.toString().trim(); }}
0 0
- Reverse Words in a String [Medium]
- [Leetcode 151, Medium] Reverse Words in a String
- Leetcode 151. Reverse Words in a String (Medium) (cpp)
- Medium 151题 Reverse Words in a String
- Medium 186题 Reverse Words in a String II
- Reverse words in a string.
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- 不忘初衷(31)
- Linux查看磁盘空间
- c# 通过NetworkInterface读取网卡Mac
- 145期马报」香港145期牌」145期马报
- OGG-00516
- Reverse Words in a String [Medium]
- 145期三中三-145期三中三
- Android Activity和Fragment的生命周期
- 我的c语言笔记---- 指针
- LeetCode: Merge Intervals
- 贝叶斯总结
- 145期六仔新粤彩145期正版挂牌出六肖145期高手解特料
- 小米模仿抄袭盗版发展线路受到重创!!
- 我是怎么让微信1天加到200个精准粉丝的