290. 单词规律
解法
python
class Solution :
def wordPattern ( self, pattern: str , s: str ) - > bool :
wordS= dict ( )
wordP= dict ( )
words= s. split( )
if len ( wordP) != len ( wordS) :
print ( 1 )
return False
for ss, p in zip ( words, pattern) :
if ( ss in wordS and wordS[ ss] != p) or ( p in wordP and wordP[ p] != ss ) :
return False
wordS[ ss] = p
wordP[ p] = ss
return True
c++
class Solution {
public :
bool wordPattern ( string pattern, string s) {
unordered_map< string, char > str2h;
unordered_map< car, string> char2h;
int m = s. length ( ) ;
int i = 0 ;
for ( auto ch: pattern) {
if ( i>= m) {
return false ;
}
int j = i
while ( j< m && s[ j] != " " ) j++ ;
const string & tmp = s. substr ( i, j- 1 ) ;
if ( str2h. count ( tmp) && str2h[ tmp] != ch) {
return false ;
}
if ( char2h. count ( ch) && char2h[ ch] != tmp) {
return false ;
}
str2h[ tmp] = ch;
char2h[ ch] = tmp;
i= j+ 1 ;
}
return true ;
}
} ;
532. 数组中的 k-diff 数对
解法
python
class Solution :
def findPairs ( self, nums: List[ int ] , k: int ) - > int :
k_diff= 0
n= 0
a= set ( nums)
a= list ( a)
if k== 0 :
b= nums
for i in a:
b. remove( i)
b= set ( b)
b= list ( b)
print ( a, nums, b)
return len ( b)
for i in a:
over_n= i+ k
low_n= i- k
n+= 1
for j in a[ n: len ( a) ] :
if j == over_n or j == low_n:
k_diff+= 1
return k_diff
c++
class Solution {
public :
int findPairs ( vector< int > & nums, int k) {
unordered_set< int > a;
unordered_set< int > b;
for ( int i : nums) {
if ( a. count ( i- k) ) {
b. emplace ( i- k) ;
}
if ( a. count ( i+ k) ) {
b. emplace ( i) ;
}
a. emplace ( i) ;
}
for ( int num : b) {
std:: cout << num << " " ;
}
return b. size ( ) ;
}
} ;