力扣基础0到1 ing...
第二题:389. 找不同
点击查看代码
class Solution {
public:
char findTheDifference(string s, string t) {
vector<int> cnt(26,0);
for(char ch:s){
cnt[ch-'a']++;
}
for(char ch:t){
cnt[ch-'a']--;
if(cnt[ch-'a']<0){
return ch;
}
}
return ' ';
}
};
带注释代码
#include <vector>
#include <string>
class Solution {
public:
char findTheDifference(string s, string t) {
// 定义一个长度为 26 的整型向量 cnt,用于统计每个小写字母的出现次数
// 初始值都设为 0,因为 'a' - 'z' 对应 0 - 25 的索引
vector<int> cnt(26, 0);
// 遍历字符串 s 中的每个字符
for (char ch : s) {
// 计算字符 ch 相对于 'a' 的偏移量,作为 cnt 向量的索引
// 并将该索引位置的计数加 1
cnt[ch - 'a']++;
}
// 遍历字符串 t 中的每个字符
for (char ch : t) {
// 计算字符 ch 相对于 'a' 的偏移量,作为 cnt 向量的索引
// 并将该索引位置的计数减 1
cnt[ch - 'a']--;
// 检查减 1 后该索引位置的计数是否小于 0
// 如果小于 0,说明该字符在 t 中出现的次数比在 s 中多,即为新添加的字符
if (cnt[ch - 'a'] < 0) {
return ch;
}
}
// 如果没有找到符合条件的字符,返回一个空格字符
// 不过在本题的实际情况中,这种情况不会发生
return ' ';
}
};
点击查看代码
class Solution {
public:
int strStr(string haystack, string needle) {
int m=haystack.size(),n=needle.size();
for(int i=0;i<m-n+1;++i){ //
bool flag=true;
for(int j=0;j<n;++j){
if(haystack[i+j]!=needle[j]){
flag=false;
break;
}
}
if(flag){
return i;
}
}
return -1;
}
};
点击查看代码
class Solution {
public:
bool isAnagram(string s, string t) {
int m = s.size(), n = t.size();
// 若两个字符串长度不同,肯定不是字母异位词
if (m != n) {
return false;
}
// 定义一个长度为 26 的向量 cnt,用于统计每个小写字母的出现次数
std::vector<int> cnt(26, 0);
// 遍历字符串 s,统计每个字符的出现次数
for (char ch : s) {
cnt[ch - 'a']++;
}
// 遍历字符串 t,将对应字符的计数减 1
for (char ch : t) {
cnt[ch - 'a']--;
// 若某个字符的计数小于 0,说明 t 中该字符的数量多于 s,不是字母异位词
if (cnt[ch - 'a'] < 0) {
return false;
}
}
// 若能遍历完 t 且没有出现计数小于 0 的情况,说明是字母异位词
return true;
}
};
点击查看代码
class Solution {
public:
bool isAnagram(string s, string t) {
if(s.length()!=t.length()){
return false;
}
sort(s.begin(),s.end());
sort(t.begin(),t.end());
return s == t;
}
};
点击查看代码
class Solution {
public:
bool isAnagram(string s, string t) {
if(s.length()!=t.length()){
return false;
}
vector<int> table(26,0);
for(auto& ch:s){
table[ch-'a']++;
}
for(auto& ch:t){
table[ch-'a']--;
if(table[ch-'a']<0){
return false;
}
}
return true;
}
};
点击查看代码
class Solution {
public:
bool repeatedSubstringPattern(string s) {
int n=s.size();
for(int i=1;i*2<=n;++i){ // i表示字串长度
if(n%i==0){
bool match=true;
for(int j=i;j<n;++j){
if(s[j]!=s[j-i]){
match=false;
break;
}
}
if(match){
return true;
}
}
}
return false;
}
};

浙公网安备 33010602011771号