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.
这个会出现内存超过的错误
public class Solution {
public string ReverseWords(string s) {
string[] d = s.Split(' ');
int lenn = d.Length;
string re = "";
for (int j = 0; j < lenn;j++ )
{
int len = d[j].Length;
char[] a = d[j].ToArray();
Array.Reverse(a);
//Console.WriteLine(string.Join("", a));
re += string.Join("", a);
re += " ";
}
return re.Substring(0,re.Length-1);
}
}
这种的遇到字符串的问题,应该用StringBuilder 代替String
public class Solution {
public string ReverseWords(string s) {
String[] words = s.Split(' ');
StringBuilder res = new StringBuilder();
for (int i = 0; i < words.Length;i++ )
{
StringBuilder tmp=new StringBuilder();
for (int j = words[i].Length-1; j >=0 ;j-- )
{
tmp.Append(words[i][j]);
}
if (i != words.Length - 1)
{
res.Append(tmp + " ");
}
else
res.Append(tmp);
}
return res.ToString();
}
}