Untitled
unknown
c_cpp
3 years ago
2.6 kB
17
Indexable
class Solution {
public:
int convert(string a){
int ans =0 ;
for(auto &i : a){
int r = i-'0' ;
ans *= 10 ;
ans += r ;
}
return ans ;
}
int get( int a , int b , char c){
if( c == '+') return b +a ;
else if( c == '-') return b-a ;
else if( c == '*') return b*a ;
else return b/a ;
}
int precedence(char c){
if( c == '+') return 1 ;
else if( c == '-') return 1 ;
else if( c == '*') return 2 ;
else return 2 ;
}
int calculate(string s) {
int n = s.size() ;
stack<char> st1 ;
stack<int> st2 ;
int i=0 ;
while(i < n){
char c = s[i] ;
if(c == ' '){
i +=1 ;
continue ;
}else if(c >= '0' && c <= '9'){
string a = "" ;
while(c >= '0' && c <= '9'){
a += c ;
i +=1 ;
}
int b = convert(a) ;
st2.push(b) ;
}else if(c == '('){
st1.push(c) ;
i += 1;
}else if(c == ')'){
while(st1.top() != '('){
char ch = st1.top() ;
st1.pop() ;
int a = st2.top() ;
st2.pop() ;
int b = st2.top() ;
st2.pop() ;
int d = get(a ,b , ch) ;
st2.push(d) ;
}
st1.pop() ;
i += 1;
}else{
while(st1.size() > 0 && st1.top() != '(' && precedence(c) <= precedence(st1.top())){
char ch = st1.top() ;
st1.pop() ;
int a = st2.top() ;
st2.pop() ;
int b = st2.top() ;
st2.pop() ;
int d = get(a ,b , ch) ;
st2.push(d) ;
}
st1.push(c) ;
i +=1 ;
}
}
while(st1.size() > 0){
char ch = st1.top() ;
st1.pop() ;
int a = st2.top() ;
st2.pop() ;
int b = st2.top() ;
st2.pop() ;
int d = get(a ,b , ch) ;
st2.push(d) ;
}
int ans = st2.top() ;
return ans ;
}
};Editor is loading...