Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Not hard to know it is simply transform from in-order to post-order.
My first idea is to build a tree from in-order string and then traverse the tree by post-order - naive so slow.
Subtle stack manipulation solves it - stack only for operators:
http://cs.nyu.edu/courses/Fall12/CSCI-GA.1133-002/notes/InfixToPostfixExamples.pdf

BTW, I love Ruby more.

 1 # SPOJ #4 QNR
 2 
 3 cnt = gets
 4 cnt = cnt.to_i
 5 
 6 #
 7 def process(str)    
 8     stk = []
 9     i = 0
10     while i < str.length do
11         c = str[i]
12         case c
13         when 'a'..'z'
14             print c        
15         when '+', '-'
16             stk.push(c)        
17         when '*', '/'
18             while !stk.empty? && (stk.last != '+' or stk.last != '-') do
19                 if(stk.last == '(')
20                     break
21                 end
22                 print stk.pop()
23             end
24             stk.push(c)        
25         when '^'
26             while !stk.empty? && stk.last == '^' do
27                 if(stk.last == '(')
28                     break
29                 end
30                 print stk.pop()
31             end
32             stk.push(c)
33         when '('
34             stk.push(c)
35         when ')'                
36             while !stk.empty? && stk.last != '(' do
37                 if(stk.last == '(')
38                     break
39                 end
40                 print stk.pop()
41             end
42             if(stk.last == '(')
43                 stk.pop()
44             end
45         end
46         i += 1
47     end    
48     while !stk.empty? do
49         print stk.pop()
50     end
51     puts
52 end # def process
53 
54 i = 0
55 while i < cnt do    
56     str = gets.to_s.downcase
57     process(str)
58     i += 1
59 end
View Code

 

posted on 2014-02-04 14:59  Tonix  阅读(179)  评论(0编辑  收藏  举报