xxxxxxxxxx
s='ccac' #output: false
t='aacc'
if set(s)==set(t) and len(s)==len(t):
d={}
e={}
for i in s:
if i not in d:
d[i]=1
else:
d[i]+=1
for i in t:
if i not in e:
e[i]=1
else:
e[i]+=1
if d != e:
print('false')
else:
print('true')
else:
print('false')
xxxxxxxxxx
from collections import Counter
def is_anagram(s1, s2):
return Counter(s1) == Counter(s2)
s1 = 'listen'
s2 = 'silent'
s3 = 'runner'
s4 = 'neuron'
print('\'listen\' is an anagram of \'silent\' -> {}'.format(is_anagram(s1, s2)))
print('\'runner\' is an anagram of \'neuron\' -> {}'.format(is_anagram(s3, s4)))
# Output
# 'listen' an anagram of 'silent' -> True
# 'runner' an anagram of 'neuron' -> False
xxxxxxxxxx
/*
Find All Anagrams in a String
Given two strings s and p, return an array of all the start
indices of p's anagrams in s. You may return the answer in any
order.
An Anagram is a word or phrase formed by rearranging the letters
of a different word or phrase, typically using all the original
letters exactly once.
*/
const findAnagrams = (s, p) => {
const [sLength, pLength] = [s.split("").length, p.split("").length]
if(pLength > sLength) return []
else {
const [subtracted, pSorted] = [sLength - pLength, p.split("").sort().join("")]
let finalResult = {
[Symbol.iterator]: function* () {
for(let i = 0; i <= subtracted; i++){
const sSliced = s.slice(i, pLength + i).split("").sort().join("")
if(sSliced === pSorted) yield i
}
}
}
return [finalResult]
}
};
const [s, p] = ["cbaebabacd", "abc"] // [0, 6]
const result = findAnagrams(s, p)
console.log(result)
// With love @kouqhar