leetcode 151. Reverse Words in a String --------- java
2024-10-19 01:23:52
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.
倒序字符串。
注意使用BufferString,因为如果使用String的话,会多次建立对象,会很慢。
public class Solution {
public String reverseWords(String s) {
int len = s.length();
if( len == 0)
return s;
StringBuffer result = new StringBuffer() ;
int end = len-1,start = 0;
while( end >= 0 && s.charAt(end) == ' ')
end--;
if( end == -1)
return result.toString();
while( start < len && s.charAt(start) == ' ')
start++;
int pos = end+1;
for( int i = end ; i >= start ; i-- ){
if( s.charAt(i) == ' ') {
result.append(s.substring(i+1,pos));
result.append(" ");
while (i < end && s.charAt(i) == ' ')
i--;
i++;
pos = i; }
}
result.append(s.substring(start,pos));
return result.toString();
}
}
最新文章
- 关于context:component-scan配置中use-default-filters参数的作用
- 安全增强 Linux (SELinux) 剖析
- [转] Matlab中给信号加高斯白噪声的方法
- xunsearch迅搜体验
- 玩转图片Base64编码
- Linux多进行之fork
- javascript优化工具 Doloto
- OpenJudge 1806:词典find()与end()
- QTP10破解方法及mgn-mqt82.exe下载
- 生成模型(generative model)与判别模型(discriminative model)的区别
- .NET手记-友盟消息推送服务器端加密算法的实现
- win7系统部分软件显示乱码怎么办
- Python的替换函数——replace(),strip(),和re.sub()
- MyEclipse移动开发教程:设置所需配置的iOS应用(三)
- CORS跨域模型浅析及常见理解误区分析
- 从一个局长使用BS系统的无奈看测试点
- ASP .NET CORE MVC 部署Windows 系统上 IIS具体步骤---.Net Core 部署到 IIS位系统中的步骤
- ECMA-Script5
- easyui学习笔记11—tab标签页和鼠标动作
- [BZOJ4000][TJOI2015]棋盘(状压DP+矩阵快速幂)