String 句子中每个单词的反义字符
句子中每个单词的反义字符。例如: 我叫亚历克斯 更改为 伊曼希勒酒店 我想到了正常的String 句子中每个单词的反义字符,string,algorithm,big-o,time-complexity,space-complexity,String,Algorithm,Big O,Time Complexity,Space Complexity,句子中每个单词的反义字符。例如: 我叫亚历克斯 更改为 伊曼希勒酒店 我想到了正常的O(n)time算法,即使用两个指针指向单词的任意一端并将其反转 但在下面的网站 (参考问题2的ans) 将其转换为链表,并对单个单词重复应用链表反转,效果更好。我在Hackerearth上为同一个程序找到了以下解决方案: public node stringReverseChars(node ll){ if(ll == null || ll.next == null) return l
O(n)
time算法,即使用两个指针指向单词的任意一端并将其反转
但在下面的网站
(参考问题2的ans)
将其转换为链表,并对单个单词重复应用链表反转,效果更好。我在Hackerearth上为同一个程序找到了以下解决方案:
public node stringReverseChars(node ll){
if(ll == null || ll.next == null)
return ll;
node tmp = ll;
node head = null, prev = null;
while(tmp != null){
while(tmp != null && tmp.data == ' '){
if(head == null)
head = tmp;
prev = tmp;
tmp = tmp.next;
}
if(tmp == null)
break;
node curr = tmp;
while(tmp.next != null && tmp.next.data != ' '){
tmp = tmp.next;
}
node np = tmp.next;
tmp.next = null;
node rev = reverseLL(curr);
if(prev != null)
prev.next = rev;
prev = curr;
curr.next = np;
if(head == null)
head = rev;
tmp = np;
}
return head;
}
此解决方案需要O(n)
时间和O(n)
空间。我建议的解决方案需要O(n)
timeO(1)
space。第二个更好吗
以下是来自Hackerearth的代码:
public node stringReverseChars(node ll){
if(ll == null || ll.next == null)
return ll;
node tmp = ll;
node head = null, prev = null;
while(tmp != null){
while(tmp != null && tmp.data == ' '){
if(head == null)
head = tmp;
prev = tmp;
tmp = tmp.next;
}
if(tmp == null)
break;
node curr = tmp;
while(tmp.next != null && tmp.next.data != ' '){
tmp = tmp.next;
}
node np = tmp.next;
tmp.next = null;
node rev = reverseLL(curr);
if(prev != null)
prev.next = rev;
prev = curr;
curr.next = np;
if(head == null)
head = rev;
tmp = np;
}
return head;
}
我很怀疑其他方法是否更好。它们具有更差的内存使用率(Θ(n)与O(1))和更差的引用位置(它们使用链表而不是数组)。我认为你的解决方案没有任何问题;事实上,我认为这是做这件事的标准方法
希望这有帮助 如果你加入代码而不是链接,你会得到更好的反应。“你需要登录/注册才能查看答案”。不会发生的,抱歉。他们说“但是有一种聪明的方法可以用递归来解决它”。在这种情况下,相反,使用递归和更少的链表没有任何好处。用来杀死苍蝇的锤子。