zoukankan      html  css  js  c++  java
  • Good Hacker——模拟&&双向队列

    题意:给定一个字符串,长度为$n(1 leq n leq 3 imes {10}^5)$,求源字符串。该字符串包括“[”(表示光标移动到最前端),“]”(移动到最后端),“>”(右移一位),“<”(左移一位),“_”(空格),"-"(backspace,删除键)。注意光标仅仅移动(或删除)当行动是有效的。

    样例:

    Sample Input 1
    subwat-y_interchange[location_]
    Sample Output 1
    location_subway_interchange
    
    Sample Input 2
    time------day___d<we>>>>nesday
    Sample Output 2
    day___wednesday
    
    Sample Input 3
    aabbcc------
    Sample Output 3
    ?

    分析:

    用python的list切片会超时,需要自己写链表,为了O(1)的维护index,采用双向链表。

    这个Python双向链表模板不错

    class Node(object):
        def __init__(self, data=None):
            self.data = data
            self.pre = None
            self.next = None
    
    
    class DoublyLinkedList(object):
        # 初始化双向链表
        def __init__(self):
            head = Node()
            tail = Node()
            self.head = head
            self.tail = tail
            self.cur = tail
            self.head.next = self.tail
            self.tail.pre = self.head
    
        # 插入节点
        def insert(self, cur, data):
            next_node = cur
            if next_node:
                node = Node(data)
                pre_node = next_node.pre
                pre_node.next = node
                node.pre = pre_node
                node.next = next_node
                next_node.pre = node
                return node
    
        # 删除节点
        def delete(self, cur):
            node = cur.pre
            if node:
                node.pre.next = node.next
                node.next.pre = node.pre
                return True
            return False
    
        # 打印链表
        def show(self, order=1):
            node = self.head.next
            while node is not self.tail:
                print(node.data, end="")
                node = node.next
    
        
    ls = DoublyLinkedList()
    str = input().strip()
    for ch in str:
        if (ch >= 'a' and ch <= 'z') or (ch == '_'):
            ls.insert(ls.cur, ch)
        elif ch == '-':
            if ls.cur.pre != ls.head:  
                ls.delete(ls.cur)
        elif ch == '<':
            if ls.cur.pre != ls.head:  
                ls.cur = ls.cur.pre
        elif ch == '>':
            if ls.cur != ls.tail: 
                ls.cur = ls.cur.next
        elif ch == '[':
            ls.cur = ls.head.next
        elif ch == ']':
            ls.cur = ls.tail
    
    if ls.head.next == ls.tail:
        print("?")
    else:
        ls.show()
  • 相关阅读:
    B/S---控件属性
    Windows Form -----内容(11)
    C#--Web控件简介
    C#控件基本1
    C#增删改小总结
    C#播放器控件的常用方法介绍
    C#封装---小练
    链接SQL、事务---小总结
    事务-----2
    事务----1
  • 原文地址:https://www.cnblogs.com/lfri/p/13283440.html
Copyright © 2011-2022 走看看