注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号
x
- #include <iostream>
- #include <cassert>
- #include <cstring>
- #include <climits>
- #include <string>
- #include <vector>
- #include <utility>
- using namespace std;
- class Solution {
- public:
- vector<int> p1(vector<int>& nums) {
- int OPT[10] = {1, 0, 0, 0, 1, 0, 1, 0, 2, 1};
- vector<int> result;
- for (const auto &i : nums) {
- string s = to_string(i);
- int val = 0;
- for (const auto &j : s) {
- int k = j - '0';
- val += OPT[k];
- }
- result.push_back(val);
- }
- return result;
- }
-
- vector<int> p2(vector<pair<string, string>>& strprs) {
- vector<int> result;
- for (const auto &i : strprs) {
- const string &s = i.first, &t = i.second;
- if (s.size() == t.size()) {
- int a[256], b[256];
- memset(a, 0, sizeof(a));
- memset(b, 0, sizeof(b));
- for (size_t j = 0; j < s.size(); j++) {
- int k = s.at(j) - 0, l = t.at(j) - 0;
- a[k]++;
- b[l]++;
- }
- int k = 0;
- for (int j = 0; j < 256; j++) {
- k += a[j] > b[j] ? a[j] - b[j] : 0;
- }
- result.push_back(k);
- }
- else {
- result.push_back(-1);
- }
- }
- return result;
- }
- size_t p3(vector<pair<int, int>> steps) {
- size_t x = INT_MAX, y = INT_MAX;
- for (const auto &i : steps) {
- x = min(x, size_t(i.first));
- y = min(y, size_t(i.second));
- }
- return x * y;
- }
- vector<string> p4(vector<string>& strs) {
- vector<string> result;
- for (const auto &i : strs) {
- int a = INT_MIN, b = INT_MIN, c = INT_MIN, d = INT_MIN;
- for (size_t j = 0, n = i.size(); j < n; j++) {
- size_t k = j;
- if (a == INT_MIN) {
- while (j < n and i.at(j) != '/') {
- j++;
- }
- a = stoi(i.substr(k, j - k));
- continue;
- }
- if (b == INT_MIN) {
- while (j < n and i.at(j) != '+') {
- j++;
- }
- b = stoi(i.substr(k, j - k));
- continue;
- }
- if (c == INT_MIN) {
- while (j < n and i.at(j) != '/') {
- j++;
- }
- c = stoi(i.substr(k, j - k));
- continue;
- }
- if (d == INT_MIN) {
- d = stoi(i.substr(k, n - k));
- continue;
- }
- }
- int x = a * d + b * c, y = b * d, r = gcd(x, y);
- result.push_back(to_string(x / r) + '/' + to_string(y / r));
- }
- return result;
- }
- private:
- int gcd(int a, int b) {
- return b == 0 ? a : gcd(b, a % b);
- }
- };
- int main(void) {
- Solution solution;
- vector<int> nums = {462, 1288, 0, 4, 6, 9, 8}, answer = {2, 4, 1, 1, 1, 1, 2}, result;
- result = solution.p1(nums);
- assert(answer == result);
- vector<pair<string, string>> strprs = {{"aabc", "abcd"}, {"ahahah", "aanannananna"}};
- answer = {1, -1};
- result = solution.p2(strprs);
- assert(answer == result);
- size_t answerL = 2, resultL = 0;
- vector<pair<int, int>> steps = {{2, 3}, {3, 7}, {4, 1}};
- resultL = solution.p3(steps);
- assert(answerL == resultL);
- vector<string> strs = {"1/2+1/3", "1/3+1/6", "3/2+1/2", "0/1+0/10"}, answerStrs = {"5/6", "1/2", "2/1", "0/1"}, resultStrs;
- resultStrs = solution.p4(strs);
- assert(answerStrs == resultStrs);
- cout << "\nPassed All\n";
- return 0;
- }
复制代码
补充内容 (2017-5-8 20:09):
g++ -signature 不一致 另外我用的C++17 所以直接照抄代码会跪掉.... |