Description:
You’re given strings J
representing the types of stones that are jewels, and S
representing the stones you have. Each character in S
is a type of stone you have. You want to know how many of the stones you have are also jewels.
The letters in J
are guaranteed distinct, and all characters in J
and S
are letters. Letters are case sensitive, so "a"
is considered a different type of stone from "A"
.
Example 1:
Input: J = "aA", S = "aAAbbbb"
Output: 3
Example 2:
Input: J = "z", S = "ZZ"
Output: 0
Note:
S
and J
will consist of letters and have length at most 50.
The characters in J
are distinct.
Language: C++
解法一:(Accepted)
思路:
遍历S中的字符,分别在J中找看存不存在(用.find(x))
class Solution {
public:
int numJewelsInStones(string J, string S) {
int result = 0;
for(int i = 0; i<S.size();i++)
{
string c = S.substr(i,1);//取S中位置i开始,长度为1的子字符串
if(J.find(c)!=string::npos) //重要!J中存在c
result++;
}
return result;
}
};
- 变式:如果description中变成不是case sensitive,即
"a"
和"A"
视为相同,应该怎么办? - 用到string type的成员函数:
string::substr(i,3)
(取位置i开始,长度为3的字符串,且代码中赋给c,c的类型只能是string,不能是char);string::find(c)
在字符串里面找子串c,如果返回string::npos
说明没找到。
解法二:用set (Accepted)
思路:
由于J
中的字母都是distinct的,想到用set容器,把J
中的字母都存在Jset
中,然后遍历字符串S
中每一个字符,如果在Jset
中找到,则result++
,最后返回。
class Solution {
public:
int numJewelsInStones(string J, string S) {
int result = 0;
set<char> Jset(J.begin(),J.end());
for(char s:S)
if(Jset.count(s))
result++;
return result;
}
};
- C++ for循环方法:
- 传统方法
for(int i; i < n; i++){}
基于范围的for循环(C++11)
//遍历数组 int array[5] = {1,2,3,4,5}; for(int &x : array)//定义范围迭代的变量x,以及迭代范围array,如果要对范围内变量进行改动,则要定义引用,如此处 x++;//每个数组元素+1 for(auto &x : array) x*=2;//auto 类型也是 C++11 新标准中的,用来自动获取变量的类型 //遍历字符串 string str("Hello Peggy!"); for(auto &c : str) c = toupper(c);//将字符串所有字符变为大写"HELLO PEGGY!"
vector, set, map的区别
Map,Set属于标准关联容器,使用了非常高效的平衡检索二叉树:红黑树,他的插入删除效率比其他序列容器高是因为不需要做内存拷贝和内存移动,而直接替换指向节点的指针即可。
Set和Vector的区别在于Set不包含重复的数据。Set和Map的区别在于Set只含有Key,而Map有一个Key和Key所对应的Value两个元素。
Map和Hash_Map的区别是Hash_Map使用了Hash算法来加快查找过程,但是需要更多的内存来存放这些Hash桶元素,因此可以算得上是采用空间来换取时间策略。- set, hash_set, map, hash_map的区别
hash_set重点在于set几个字母上,主要实现集合功能,只不过底层函数由hashtable提供,而set是由红黑树作底层,两者的唯一区别就是set默认是排好序的,而hashset不是。
hashmap重点在于map几个字母上,主要提供对象间的一一映射功能,hashmap底层由hashtable提供,而map底层由红黑树提供,区别同上。