这一篇开始介绍一下字符串常见的算法实现
LeetCode 面试题 01.04. 回文排列
/* 给定一个字符串,编写一个函数判定其是否为某个回文串的排列之一
通过计数的方式判断,回文串必定是有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. 字符串相加
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;
}
};
如有侵权,请联系删除,如有错误,欢迎大家指正,谢谢