您的位置:首页 > 其它

leetcode题解-151. Reverse Words in a String && 557. Reverse Words in a String III

2017-11-07 10:56 411 查看
这两道题目都是反转字符串中单词类型的,II收费所以没刷,先看着两道。

151, Reverse Words in a String,题目:

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.


本题是将字符串中的所有单词反向排列,很简单,直接split即可,但是要注意单词之间可能会有多个空格,而且字符串的开头和结尾也都可能会出现空格,所以要先trim在split,而且切分的时候要对多个空格进行匹配切分,不能只对单个空格切分。代码如下所示:

public String reverseWords(String s) {
String[] words = s.trim().split(" +");
StringBuilder res = new StringBuilder();
for(int i=words.length - 1; i > 0; i--)
res.append(words[i] + " ");
res.append(words[0]);
return res.toString();
}


此外,我们也可以不适用内置的切分函数,自己按照字符串进行切分并重新拼接,代码效率会略有提升,如下所示:

public static String reverseWords1(String s) {
if (s == null)
return null;

char[] str = s.toCharArray();
int start = 0, end = str.length - 1;

// Trim start of string
while (start <= end && str[start] == ' ')
start++;

//Trim end of string
while (end >= 0 && str[end] == ' ')
end--;

if (start > end)
return new String("");

int i = start;
while (i <= end) {
if (str[i] != ' ') {
// case when i points to a start of word -  find the word reverse it
int j = i + 1;
while (j <= end && str[j] != ' ')
j++;
reverse(str, i, j - 1);
i = j;
} else {
if (str[i - 1] == ' ') {
//case when prev char is also space - shift char to left by 1 and decrease end pointer
int j = i;
while (j <= end - 1) {
str[j] = str[j + 1];
j++;
}
end--;
} else
// case when there is just single space
i++;
}
}
//Now that all words are reversed, time to reverse the entire string pointed by start and end - This step reverses the words in string
reverse(str, start, end);
// return new string object pointed by start with len = end -start + 1
return new String(str, start, end - start + 1);
}

private static void reverse(char[] str, int begin, int end) {
while (begin < end) {
char temp = str[begin];
str[begin] = str[end];
str[end] = temp;
begin++;
end--;
}
}


557,Reverse Words in a String III,题目:

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:
Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not be any extra space in the string.


本提就跟家简单了,每个单词都以空格分开,需要做的就是将每个单词进行反向翻转,代码如下,可以击败35%的用户:

public static String reverseWords(String s) {
if(s.equals("") || s.equals(" "))
return s;
char[] ss = s.toCharArray();
int i = 0, j;
StringBuilder res = new StringBuilder();
while(i<ss.length){
j=i;
while(j < ss.length && ss[j] != ' ') j++;
res.append(reverse(ss, i, j-1));
res.append(" ");
i=j+1;
}
res.deleteCharAt(ss.length);
return res.toString();
}

public static String reverse(char[] ss, int i, int j){
String res = "";
for(int k=j; k>=i; k--)
res += ss[k];
return res;
}


还有一种更为简洁的方法,使用内置的reverse函数进行翻转,效率略有提升,可以击败60%的用户:

public String reverseWords1(String s) {
String[] str = s.split(" ");
for (int i = 0; i < str.length; i++) str[i] = new StringBuilder(str[i]).reverse().toString();
StringBuilder result = new StringBuilder();
for (String st : str) result.append(st + " ");
return result.toString().trim();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: