1 题目
给出两个字符串J和S,输出字符串S中包含J中字符的个数,如J="Az", S="AzzZZZ",则输出3;
2 解答
package com.jewels;
public class test {
private static int jewels_cnt(String J, String S) {
int cnt = 0;
for (int i=0; i<S.length(); i++) {
if (J.indexOf(S.charAt(i)) > -1){
cnt++;
}
}
return cnt;
}
public static void main(String[] argv) {
String j = "az";
String s = "azzzzzz";
System.out.println("jewels cnt is " + jewels_cnt(j, s));
}
}
3 总结
- 函数str.indexOf(char),用于计算字符char在字符串str中的位置,若是不存在则返回-1。
- 还有另外一个类似的函数str.contains(String.valueOf(char)),用于判断字符是否在字符串里面,但是通过在leetcode测试时候发现比indexOf的效率低,这个函数主要用于子字符串的判断。
- str.charAt(i)用于取字符串的元素的。
- char是基本类型,Character是类类型。