Reverse Words
2015-07-13 08:10
281 查看
Reverse Words
Write a function that reverses the order of the words in a string. For example
4000
, your function should transform the string “Do or do not, there is no try.” to “try. no is there not, do or Do”. Assume that all words are space delimited
and treat punctuation the same as letters.
class Solution {
public static String reverseWords(char[] str) {
if (str == null || str.length == 0)
return null;
reverseStr(str, 0, str.length - 1);
int start = 0;
int end = 0;
while (end < str.length) {
if (str[end] != ' ') {
start = end;
while ( end < str.length && str[end] != ' ')
end++;
end--;
reverseStr(str, start, end);
}
end++;
}
return new String(str);
}
private static void reverseStr(char[] str, int start, int end) {
while (end > start) {
char temp = str[start];
str[start] = str[end];
str[end] = temp;
end--;
start++;
}
}
public static void main(String[] args) {
String str = "Do or do not, there is no try.";
char[] ch = str.toCharArray();
System.out.print(reverseWords(ch));
}
}
Write a function that reverses the order of the words in a string. For example
4000
, your function should transform the string “Do or do not, there is no try.” to “try. no is there not, do or Do”. Assume that all words are space delimited
and treat punctuation the same as letters.
class Solution {
public static String reverseWords(char[] str) {
if (str == null || str.length == 0)
return null;
reverseStr(str, 0, str.length - 1);
int start = 0;
int end = 0;
while (end < str.length) {
if (str[end] != ' ') {
start = end;
while ( end < str.length && str[end] != ' ')
end++;
end--;
reverseStr(str, start, end);
}
end++;
}
return new String(str);
}
private static void reverseStr(char[] str, int start, int end) {
while (end > start) {
char temp = str[start];
str[start] = str[end];
str[end] = temp;
end--;
start++;
}
}
public static void main(String[] args) {
String str = "Do or do not, there is no try.";
char[] ch = str.toCharArray();
System.out.print(reverseWords(ch));
}
}
相关文章推荐
- IOS开发 - 05 通过Xib创建自定义视图
- oracle默认管理员的帐号和密码以及密码修改和解除锁定
- 增强图文件
- 第七章 深入理解多态
- MyBatis Mapper 文件例子
- IOS开发 - 04.自定义视图
- 修改 Ubuntu 桌面分辨率
- IOS开发- 03.字典转模型
- 实验二:使用Scanner 和println
- VC单文档实现多视图的方法
- Reverse Words in a String
- 好用免费外文文献
- IOS开发 - 01.九宫格实现原理
- 更好的设计你的 REST API
- Activity生命周期(1)
- 上周热点回顾(7.6-7.12)
- 使用ASP.NET web API创建REST服务(二)
- ASP.NET Web API与Rest web api(一)
- LFS 中文版手册发布:如何打造自己的 Linux 发行版
- scikit-learn:从文本文件中提取特征(tf、idf)