20.Valid Parentheses
【题目】
You're given stringsJ
representing the types of stones that are jewels, andS
representing the stones you have. Each character inS
is a type of stone you have. You want to know how many of the stones you have are also jewels.
The letters inJ
are guaranteed distinct, and all characters inJ
andS
are letters. Letters are case sensitive, so"a"
is considered a different type of stone from"A"
.
給定字符串J代表石頭中寶石的類型,和字符串S代表你擁有的石頭。S中每個字符代表了一種你擁有的石頭的類型,
你想知道你擁有的石頭中有多少是寶石。
J中的字母不重複,J和S中的所有字符都是字母。字母區分大小寫,因此“a”和“A”是不同類型的石頭。
Example 1:
Input:
J = "aA", S = "aAAbbbb"
Output:
3
Example 2:
Input:
J = "z", S = "ZZ"
Output:
0
【思路】
這題先了解題目的要求, J 的字串代表目標,但是拆開來的,所以例題 aA 代表要找 a 和 A 兩種加總,簡單!
【解法】
☆JAVA
JAVA應用indexOf,如果此字符串中沒有這樣的字符,則返回-1,所以 只要取出條件字符一個一個去問J有沒有存在就好嚕
public static int numJewelsInStones2(String J, String S) {
int Jint = 0;
for(char temp : S.toCharArray()){
if( J.indexOf(temp) != -1){
Jint++;
}
}
return Jint;
}
☆Python
跟JAVA解法相同 只是indexof改用in去比對
list = 切割為各個字串的array , in 等同於 contain
def numJewelsInStones(self, J, S):
result = 0;
JString = list(J);
for i in range(len(S)):
if( S[i] in JString):
result = result +1;
return result;