哈希集合
public static int numJewelsInStones ( String J, String S) {
int lenj= J. length ( ) ;
int sum= 0 ;
Set< Character> hashMap= new HashSet < > ( lenj- 1 ) ;
for ( int x= 0 ; x< lenj; x++ ) {
hashMap. add ( J. charAt ( x) ) ;
}
for ( int i= 0 ; i< S. length ( ) ; i++ ) {
if ( hashMap. contains ( S. charAt ( i) ) ) {
sum++ ;
continue ;
}
}
return sum;
}
暴力求解
public static int numJewelsInStones ( String J, String S) {
int sum= 0 ;
for ( int i= 0 ; i< S. length ( ) ; i++ ) {
for ( int j= 0 ; j< J. length ( ) ; j++ ) {
if ( S. charAt ( i) == J. charAt ( j) ) {
sum++ ;
break ;
}
}
}
return sum;
}
正则表达式
public static int numJewelsInStones ( String J, String S) {
return S. replaceAll ( "[^" + J+ "]" , "" ) . length ( ) ;
}
集合set
public static int numJewelsInStones ( String J, String S) {
int sum= 0 ;
Set< Character> set = new HashSet ( ) ;
char [ ] charj= J. toCharArray ( ) ;
char [ ] chars= S. toCharArray ( ) ;
for ( char j: charj)
set. add ( j) ;
for ( char s: chars)
if ( set. contains ( s) )
sum++ ;
return sum;
}
学以致用
replaceAll(regex,replacement)
S. replaceAll ( "[^" + J+ "]" , "" )
contains()判断字符串中是否有子字符串,返回值为boolean类型 HashMap使用put,HashSet使用add录入数据 HashMap使用containsKey,HashSet使用contain查询是否存在