官方网站建设与维护好处,济南优化seo网站建设,广告公司平面设计培训,建网站系统平台欢迎来到Cefler的博客#x1f601; #x1f54c;博客主页#xff1a;那个传说中的man的主页 #x1f3e0;个人专栏#xff1a;题目解析 #x1f30e;推荐文章#xff1a;【LeetCode】winter vacation training 目录 #x1f449;#x1f3fb; 有效的字母异位词#x… 欢迎来到Cefler的博客 博客主页那个传说中的man的主页 个人专栏题目解析 推荐文章【LeetCode】winter vacation training 目录 有效的字母异位词 判断字符串的两半是否相似 有效的字母异位词 字符串解码 有效的字母异位词
原题链接有效的字母异位词
mycode:
class Solution {
public:bool isAnagram(string s, string t) {mapchar,int ms;for(auto e:s){ms[e];}for(auto e:t){ms[e]--;}for(auto e:ms){if(e.second!0)return false;}return true;}
};判断字符串的两半是否相似
原题链接判断字符串的两半是否相似
mycode:
class Solution {
public:bool halvesAreAlike(string s) {string str aeiouAEIOU;int half s.size()/2;string left s.substr(0,half),right s.substr(half);int count1 0,count2 0;for(int i 0;ihalf;i){if((string(1,left[i])).find_first_of(str)!string::npos)count1;if((string(1,right[i])).find_first_of(str)!string::npos)count2;}if(count1count2)return true;else return false;}
};substr是C中的一个字符串操作函数用于从给定字符串中提取子字符串。
substr函数的语法如下
string substr(size_t pos 0, size_t count npos) const;参数说明
pos要提取子字符串的起始位置。默认为0表示从字符串的开头开始。count要提取的字符数。默认为npos表示提取从起始位置到字符串末尾的所有字符。
substr函数返回一个新的string对象其中包含了从原始字符串中提取的子字符串。
以下是一个使用substr函数的示例
#include iostream
#include stringusing namespace std;int main() {string str Hello, World!;string sub1 str.substr(7); // 从位置7开始提取子字符串cout sub1: sub1 endl; // 输出: World!string sub2 str.substr(0, 5); // 从位置0开始提取5个字符的子字符串cout sub2: sub2 endl; // 输出: Helloreturn 0;
}输出结果
sub1: World!
sub2: Hello在上面的示例中我们定义了一个字符串str然后使用substr函数从该字符串中提取了两个子字符串。第一个子字符串sub1从位置7开始提取即字符串中的World!部分。第二个子字符串sub2从位置0开始提取提取了前5个字符即字符串中的Hello部分。
需要注意的是substr函数返回的是一个新的string对象原始字符串本身并没有改变。 有效的字母异位词
原题链接有效的字母异位词
mycode:
class Solution {
public:bool checkAlmostEquivalent(string word1, string word2) {mapchar,int w1,w2;for(auto e:word1) w1[e];for(auto e:word2) w2[e];for(auto x:w1)if(x.second-w2[x.first]3)return false;for(auto x:w2)if(x.second-w1[x.first]3)return false;return true;}
};官方题解
class Solution {
public:bool checkAlmostEquivalent(string word1, string word2) {unordered_mapchar, int freq; // 频数差哈希表for (auto ch: word1){freq[ch];}for (auto ch: word2){--freq[ch];}// 判断每个字符频数差是否均小于等于 3return all_of(freq.begin(), freq.end(), [](auto x) { return abs(x.second) 3; });}
};字符串解码
原题链接字符串解码
mycode: