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); } };
总想把每一篇文章精雕细琢之后以完美的面貌示人,就像演员在演出前都要彩排,总想准备好之后再去展现精彩的一面,但人生的每一刻都是精彩的,就算现在还不完善也要发出来,作为自己一直在学习的一种见证。