1. 程式人生 > 實用技巧 >Good Hacker——模擬&&雙向佇列

Good Hacker——模擬&&雙向佇列

題意:給定一個字串,長度為$n(1 \leq n \leq 3 \times {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()