华为机试:求字符串中所有整数的最小和

题目来源

  • 华为机试:求字符串中所有整数的最小和

题目描述

华为机试:求字符串中所有整数的最小和_第1张图片
华为机试:求字符串中所有整数的最小和_第2张图片

题目解析

  • 如果是负数的话,负数越大,和最小
  • 如果是正数的话, nums[0] + nums[1] +… + nums[i] < nums[0…i]
#include
#include 

using namespace std;

class Solution {
public:
    int process(std::string str){
        std::vector<int> pos;
        std::vector<int> neg;
        int i = 0;
        while (i < str.size()){
            if((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z') ){
                i = i + 1;
                continue;
            }

            if(str[i] != '-'){
                pos.push_back(str[i] - '0');
                i++;
                continue;
            }

            // ---------------
            if(i + 1 == str.size()){
                i = i + 1;
                continue;
            }

            if(!isdigit(str[i + 1])){  // -a
                i = i + 2;
                continue;
            }
            // -000456a
            int j = i + 1;
            while (j < str.size() && isdigit(str[j])){
                j++;
            }
            auto tmp = str.substr(i, j - i);
            neg.push_back(stoi(tmp));
            i = j;
        }

        int sum = 0;
        for (int po : pos) {
            sum += po;
        }
        for (int n : neg) {
            sum += n;
        }

        return sum;
    }
};


int main()
{
    Solution obj;
    std::cout << obj.process("bb12-34aa");
}

你可能感兴趣的:(算法与数据结构,算法)