我对这个问题的一个答案有一个小问题。 问题就像
给定一个输入字符串,逐字反转该字符串。
例如, 给定 s =“天空是蓝色的”, 返回“蓝色是天空”。
答案是
public class Solution {
public String reverseWords(String s) {
s = s.trim();
return helper(s,0).toString();}
private StringBuilder helper(String s, int index){
if(index>=s.length())
return new StringBuilder();
StringBuilder cur = new StringBuilder();
int lastIndex = index;
while(index < s.length() && s.charAt(index)!=' ')
{
cur.append(s.charAt(index++));
}
while(index < s.length() && s.charAt(index)==' ')
index++;
if(lastIndex == 0)
return helper(s,index).append(cur);
return helper(s,index).append(cur).append(' ');}
我对这段代码的最后一行有疑问。为什么append(cur)在append('')之前?不应该是之后吗?
最佳答案
考虑这部分代码:
if(lastIndex == 0)
return helper(s,index).append(cur);
return helper(s,index).append(cur).append(' ');
第一次调用 helper 时,条件 (lastIndex == 0)
为 true,在这种情况下,cur
包含第一个单词,并且 helper(s ,index)
以相反的顺序返回剩余的单词。
由于您在本例中将第一个单词附加到反向 StringBuilder
的其余部分而不添加空格,这意味着 helper(s,index)
必须在反转的子字符串后面添加一个空格。
例如,假设您有一个字符串:
一二三
helper(s,index)
必须返回“Three Two”,您可以在其中附加“One”以获取反转的字符串。
对 helper 的下一次调用将返回“Three”,您可以在其中附加“Two”,然后添加一个空格。
下一次调用将返回一个空的 StringBuilder,您可以在其中附加“Three”,然后添加一个空格。
您可以用这一行替换上面的 3 行:
return helper(s,index).append(' ').append(cur);
但是,在这种情况下,输出将在开头有一个额外的空格,因为最后一次调用 helper
返回一个空的 StringBuilder,因此如果您在其后面附加一个空格,该空格将是输出的第一个字符。
您可以添加不同的条件来消除多余的空间:
StringBuilder sub = helper(s,index);
if (sub.length() > 0)
sub.append(' '); // append a space only if it's not the
// first char of the output
return sub.append(cur);
关于java - leetcode上字符串中反向词的一行代码序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28128439/