【哈希表】leetcode_383_赎金信
python(字符串str的删除指定元素可以用replace(new,old,count)
class Solution :
def canConstruct ( self, ransomNote: str , magazine: str ) - > bool :
for i in ransomNote:
if i in magazine:
magazine = magazine. replace( i, "" , 1 )
else :
return False
return True
c++(set法)
class Solution {
public :
bool canConstruct ( string ransomNote, string magazine) {
multiset< char > magazine_se ( magazine. begin ( ) , magazine. end ( ) ) ;
for ( int i= 0 ; i< ransomNote. size ( ) ; i++ ) {
multiset< char > :: iterator fi = magazine_se. find ( ransomNote[ i] ) ;
if ( fi != magazine_se. end ( ) ) {
magazine_se. erase ( fi) ;
} else {
return false ;
}
}
return true ;
}
} ;
数组就是哈希表法(因为都是小写字母,数据有限,数组性能更好)
class Solution {
public :
bool canConstruct ( string ransomNote, string magazine) {
int re[ 26 ] = { } ;
for ( char i : magazine) {
re[ i - 'a' ] ++ ;
}
for ( char j : ransomNote) {
re[ j - 'a' ] -- ;
if ( re[ j - 'a' ] < 0 ) {
return false ;
}
}
return true ;
}
} ;