> 技术文档 > 力扣682. 棒球比赛

力扣682. 棒球比赛

力扣682. 棒球比赛
力扣682. 棒球比赛
这一题的思路很简单,很明显的可以看出来是用栈模拟,
唯一需要注shu意的是开int是不够的,用开longlong
字符串转数字的方法要熟练掌握:

string s;int result=0;int flag=0;for(int i=0;i<s.size();i++){ if(s[i]==\'-\') { flag=1; continue; } else { result=result*10+(s[i]-\'0\'); }}if(flag==1){result=-result;}

最好不要用stoi和stoll,而是自己手写,自己手写的速度更快。
完整代码如下:

class Solution {public: stack<int> s;int calPoints(vector<string>& operations) { long long ans=0;for(int i=0;i<operations.size();i++) { if(operations[i]==\"+\") { long long a=s.top(); s.pop(); long long b=s.top(); s.pop(); ans+=a+b; s.push(b); s.push(a); s.push(a+b); } else if(operations[i]==\"D\") {  long long x=s.top();  ans+=x*2;  s.push(x*2); } else if(operations[i]==\"C\") { ans-=s.top(); s.pop(); } else { long long result=0; //让字符串转换成数字 int flag=0; for(int j=0;j<operations[i].size();j++) {  if(operations[i][j]==\'-\')  {  flag=1;  //说明是一个负数continue; }  result=result*10+operations[i][j]-\'0\';  } if(flag==1) { result=result*(-1);} s.push(result); ans+=result; } } return ans; }};