Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 7ca283e

Browse files
zhangzz2015gitbook-bot
authored andcommitted
GitBook: [greyireland#104] No subject
1 parent 79bcda8 commit 7ca283e

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed

‎data_structure/stack_queue.md‎

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,91 @@ public:
210210
};
211211
```
212212
213+
Basic Calculator
214+
215+
```cpp
216+
// Some code
217+
class Solution {
218+
public:
219+
int calculate(string s) {
220+
s.push_back('+');
221+
int start =0;
222+
return dfs(s, start);
223+
}
224+
225+
226+
int dfs(string& s, int & start)
227+
{
228+
int num =0;
229+
230+
vector<int> stack;
231+
char sign = '+';
232+
while(start<s.size())
233+
{
234+
if(isdigit(s[start]) )
235+
{
236+
num = (num*10 + (s[start]-'0'));
237+
}
238+
else if(s[start] == '+' ||
239+
s[start] == '-' ||
240+
s[start] == '*' ||
241+
s[start] == '/' )
242+
{
243+
if(sign == '+')
244+
stack.push_back(num);
245+
else if(sign == '-')
246+
stack.push_back(-num);
247+
else if(sign == '*')
248+
{
249+
int prev = stack.back();
250+
stack.pop_back();
251+
stack.push_back(prev*num);
252+
}
253+
else if(sign == '/')
254+
{
255+
int prev = stack.back();
256+
stack.pop_back();
257+
stack.push_back(prev/num);
258+
}
259+
num =0;
260+
sign = s[start];
261+
}
262+
else if(s[start]=='(')
263+
{
264+
start++;
265+
num = dfs(s, start);
266+
}
267+
else if(s[start]==')')
268+
{
269+
if(sign == '+')
270+
stack.push_back(num);
271+
else if(sign == '-')
272+
stack.push_back(-num);
273+
else if(sign == '*')
274+
{
275+
int prev = stack.back();
276+
stack.pop_back();
277+
stack.push_back(prev*num);
278+
}
279+
else if(sign == '/')
280+
{
281+
int prev = stack.back();
282+
stack.pop_back();
283+
stack.push_back(prev/num);
284+
}
285+
break;
286+
}
287+
start++;
288+
}
289+
int sum =0;
290+
for(int i=0; i< stack.size(); i++)
291+
sum+=stack[i];
292+
return sum;
293+
294+
}
295+
};c++
296+
```
297+
213298
利用栈进行 DFS 递归搜索模板
214299

215300
```go

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /