您的位置:首页 > 编程语言 > Java开发

[leetcode]151. Reverse Words in a String@Java解题报告

2017-07-29 11:35 537 查看
https://leetcode.com/problems/reverse-words-in-a-string/tabs/description

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.

思路

这道题让我们翻转字符串中的单词,题目中给了我们写特别说明,如果单词之间遇到多个空格,只能返回一个,而且首尾不能有单词,并且对C语言程序员要求空间复杂度为O(1),我是用Java写的,就不考虑这个问题了。

先整个字符串整体翻转一次,然后再分别翻转每一个单词(或者先分别翻转每一个单词,然后再整个字符串整体翻转一次),此时就能得到我们需要的结果了。代码如下:

package go.jacob.day729;

/**
* 151. Reverse Words in a String
*
* @author Jacob
*
*/
public class Demo2 {
public String reverseWords(String s) {
if (s == null || s.length() < 2)
return s;
char[] arr = s.toCharArray();
int left = 0, right = s.length() - 1;
// 完全翻转
reverse(arr,left,right);
//翻转单个单词
reverseWord(arr);
//空格处理
return cleanSpaces(arr);
}

private String cleanSpaces(char[] arr) {
int n=arr.length;
int i=0,j=0;
while(j<n){
while(j<n&&arr[j]==' ')
j++;
while(j<n&&arr[j]!=' '){
arr[i++]=arr[j++];
}
while(j<n&&arr[j]==' ')
j++;
if(j<n)
arr[i++]=' ';
}
return new String(arr).substring(0,i);
}

private void reverseWord(char[] arr) {
int n=arr.length,i=0,j=0;
while(j<n){
while(i<j||i<n&&arr[i]==' ')
i++;
while(j<i||j<n&&arr[j]!=' ')
j++;
reverse(arr,i,j-1);
}
}
//翻转left到right间的字母
private void reverse(char[] arr, int left, int right) {
while(left<right){
char temp=arr[left];
arr[left]=arr[right];
arr[right]=temp;
left++;
right--;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: