Reverse Words in a String
反转一个字符串
垃圾方法:
#include <sstream> #include <vector> class Solution { public: void reverseWords(string &s) { istringstream is(s); string word; vector<string> dict; while (is >> word) { dict.push_back(word); } string ret = ""; for (int i = dict.size() - 1; i > 0; --i) { ret = ret + dict[i] + " "; } if (dict.size() > 0) ret += dict[0]; s = ret; } };
Evaluate Reverse Polish Notation
简单计算器
class Solution { public: int evalRPN(vector<string> &tokens) { stack<int> s; for (int i = 0; i < tokens.size(); ++i) { if (tokens[i] != "+" && tokens[i] != "-" && tokens[i] != "*" && tokens[i] != "/") { s.push(s2i(tokens[i])); } else { int a = s.top(); s.pop(); int b = s.top(); s.pop(); if (tokens[i] == "-") s.push(b - a); if (tokens[i] == "+") s.push(b + a); if (tokens[i] == "*") s.push(b * a); if (tokens[i] == "/") s.push(b / a); } } return s.top(); } int s2i(string &token) { bool sign = true; if (token[0] == '-') sign = false; int b = 1; int ret = 0; int end = sign ? 0 : 1; for (int i = token.size() - 1; i >= end; --i) { ret += b * (token[i] - '0'); b *= 10; } return sign ? ret : (-ret); } };