eg: "nasa" output: 'n'
Require to scan the string only once.
思路:要求只能扫一遍string,既然时间严格限制,那只好多用空间了。一个map用来计数,一个double linkedlist用来存character candidates.最后总时间是O(n).
注:本代码未测试,懒得自己写double linked node的定义了。。
- //assume that s is nonempty
- char firstnondup(string s){
- unordered_map<char, ListNode*> visited;
- ListNode *tail = new ListNode(s[0]);
- ListNode dummy(0);
- dummy.next = tail;
- tail->prev = dummy;
- visited[s[0]] = tail;
- for(int i = 1; i < s.length(); i++){
- //if first occured
- if(visited.find(s[i]) == visited.end()){
- ListNode *cur = new ListNode(s[i]);
- visited[s[i]] = cur;
- tail->next = cur;
- cur->prev = tail;
- tail = cur;
- }
- else{
- //if second occured, delete node
- if(visited[s[i]] != NULL) {
- ListNode *tmp = visited[s[i]]->prev;
- tmp->next = visited[s[i]]->next;
- visited[s[i]]->next->prev = tmp;
- if(visited[s[i]] == tail) tail = tmp;
- delete visited[s[i]];
- }
- //if more than secondly occured, just continue
- }
- }
- return dummy.next.val;
- }
No comments:
Post a Comment