String common algorithm implementation (1)

This article begins to introduce the common algorithm implementation of strings

LeetCode Interview Questions 01.04. Palindrome arrangement

/* 给定一个字符串,编写一个函数判定其是否为某个回文串的排列之一 
   通过计数的方式判断,回文串必定是有0或1个出现奇数次的字符 
   */
class Solution {
    
    
public:
    bool canPermutePalindrome(string s) {
    
    
        if (s.empty()) {
    
    
            return true;
        }
        vector<int> nums(128, 0);
        for (auto c : s) {
    
    
            nums.at(c)++;
        }
        int num = 0;
        for (auto e : nums) {
    
    
            num += e % 2 == 0 ? 0 : 1;
        }
        return num == 0 || num == 1;
    }
};

LeetCode 415. String addition

class Solution {
    
    
public:
    string addStrings(string num1, string num2) {
    
    
        if (num1.empty() || num2.empty()) {
    
    
            return num1.empty() ? num2 : num1;
        }
        string res;
        int carry = 0;
        int i1 = num1.length() - 1;
        int i2 = num2.length() - 1;
        while (i1 >= 0 || i2 >= 0 || carry > 0) {
    
    
            if (i1 >= 0) {
    
    
                carry += num1.at(i1--) - '0';
            }
            if (i2 >= 0) {
    
    
                carry += num2.at(i2--) - '0';
            }
            res.append(to_string(carry%10));
            carry /= 10;
        }
        reverse(res.begin(), res.end());
        return res;
    }
};

If there is any infringement, please contact to delete it. If there is an error, please correct me, thank you

Guess you like

Origin blog.csdn.net/xiao_ma_nong_last/article/details/105173890