【发布时间】:2014-05-22 09:51:10
【问题描述】:
反转句子中每个单词的字符。例如:
我叫亚历克斯
更改为
yM 男人 si xela
我想到了普通的O(n)时间算法,使用两个指针指向单词的任一端并反转它。
但在下面的网站
(参考问题 2 的答案) 将其转换为链表并为单个单词重复应用链表的反转效果更好。我在 Hackerearth 上为同一程序找到了以下解决方案:
http://learn.hackerearth.com/question/317/reverse-characters-of-each-word-in-a-sentence/
此解决方案需要O(n) 时间和O(n) 空间。我建议的解决方案需要O(n) 时间O(1) 空间。第二个怎么样?
以下是来自 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;
}
【问题讨论】:
-
如果你包含代码而不是链接,你会得到更好的反应。
-
“您需要登录/注册才能查看答案”。不会发生的,对不起。
-
他们说“但是有一种聪明的方法可以使用递归来解决它”。在这种情况下,使用递归甚至更少的链表没有任何好处,相反。杀死苍蝇的锤子。
标签: string algorithm big-o time-complexity space-complexity