问题描述
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.
解决方法
//方法1
class Solution
{
public static String reverseWords(String s)
{
int start = 0;
int end;
char[] c = s.toCharArray();
String s1 = "";
for(int i=0; i<s.length(); i++)
{
if(c[i] == ' ')
{
end = i-1;
reverse(c, start, end);
start = i+1;
}
if(i == c.length - 1)
{
end = i;
reverse(c, start, end);
}
}
return new String(c);
}
private void reverse(char[] a, int start, int end)
{
for(; start<end; start++,end--)
{
char tmp = a[start];
a[start] = a[end];
a[end] = tmp;
}
}
}
/*方法2:先将字符串按照空格进行分割为字符串数组,然后将每个字符串作为参数传到新建的StringBuilder对象中,之后求其逆串,最后转为String。然后使用append加上空格,最后使用trim消除多余的空格。*/
class Solution
{
public String reverseWords(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();
}
}
//方法3,和方法1类似
class Solution
{
public String reverseWords(String s)
{
char[] s1 = s.toCharArray();
int i = 0;
for(int j = 0; j < s1.length; j++)
{
if(s1[j] == ' ')
{
reverse(s1, i, j - 1);
i = j + 1;
}
}
reverse(s1, i, s1.length - 1);
return new String(s1);
}
public void reverse(char[] s, int l, int r)
{
while(l < r)
{
char temp = s[l];
s[l] = s[r];
s[r] = temp;
l++; r--;
}
}
}
//方法4,和方法1类似
public class Solution
{
public String reverseWords(String s) {
char[] ca = s.toCharArray();
for (int i = 0; i < ca.length; i++) {
if (ca[i] != ' ') { // when i is a non-space
int j = i;
while (j + 1 < ca.length && ca[j + 1] != ' ') { j++; } // move j to the end of the word
reverse(ca, i, j);
i = j;
}
}
return new String(ca);
}
private void reverse(char[] ca, int i, int j) {
for (; i < j; i++, j--) {
char tmp = ca[i];
ca[i] = ca[j];
ca[j] = tmp;
}
}
}
出现的问题
以下程序提交出现超时的错误:
Submission Result: Time Limit Exceeded
class Solution
{
public static String reverseWords(String s)
{
int start = 0;
int end;
char[] c = s.toCharArray();
String s1 = "";
for(int i=0; i<s.length(); i++)
{
if(c[i] == ' ')
{
end = i-1;
for(int j=end; j>=start; j--)
s1 += c[j];
s1 += " ";
start = i+1;
}
if(i == c.length - 1)
{
end = i;
for(int j=end; j>=start; j--)
s1 += c[j];
}
}
return s1;
}
}
原因:http://blog.csdn.net/GSH_Hello_World/article/details/78599162