【问题标题】:Reverse characters of each word in a sentence反转句子中每个单词的字符
【发布时间】:2014-05-22 09:51:10
【问题描述】:

反转句子中每个单词的字符。例如:

我叫亚历克斯

更改为

yM 男人 si xela

我想到了普通的O(n)时间算法,使用两个指针指向单词的任一端并反转它。

但在下面的网站

http://www.businessinsider.com/8-mind-bending-interview-questions-that-google-asks-its-engineers-2012-7?op=1

(参考问题 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


【解决方案1】:

我很怀疑其他方法是否更好。它们的内存使用更差(Θ(n) 与 O(1))和更差的引用局部性(它们使用链表而不是数组)。我认为您的解决方案没有任何问题;事实上,我认为这是执行此操作的标准方式。

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2012-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-02
    • 1970-01-01
    • 2013-08-07
    相关资源
    最近更新 更多