【LeetCode】winter vacation training

在这里插入图片描述

欢迎来到Cefler的博客😁
🕌博客主页:那个传说中的man的主页
🏠个人专栏:题目解析
🌎推荐文章:【LeetCode】winter vacation training

在这里插入图片描述


目录

  • 👉🏻 有效的字母异位词
  • 👉🏻 判断字符串的两半是否相似

👉🏻 有效的字母异位词

原题链接:有效的字母异位词

mycode:

class Solution {
public:bool isAnagram(string s, string t) {map<char,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;i<half;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(count1==count2)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 <string>using 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对象,原始字符串本身并没有改变。