cola

cola

Enjoy Coding Everywhere 👻

Anagram of a string

Given a string "abc", determine if it is an anagram of the string "adcba".

A straightforward solution to this problem is to use two pointers. First, use a map to record the count of each character in s1. Then, iterate through s2, and for each iteration, start the two pointers, with start as the current index and end as start + s1.length. The length of this interval is the same as s1, so we only need to update the map list. When the two pointers finish, if the map is all 0, then s2 is a substring of s1 and is an anagram.

The following solution is similar to the previous one.

// All values in the map are 0
function everyZero(map){
  return Object.values(map).every(i => i===0)
}
function solve(s1, s2) {
  if(typeof s1 !== 'string' || typeof s2 !== 'string') return false
  if(s1.length > s2.length) return false
  const map = {};
  // Iterate through s1, use each character as the key to store the count of characters
  s1.split('').map((i, index)=>{
    if(!map[i]) map[i] = 0
    map[i]++
    // When encountering a character in s2, decrease the count
    if(!map[s2[index]]) map[s2[index]] = 0
    map[s2[index]]--
  })
  // Check if there is an anagram at the beginning
  const bool = everyZero(map)
  if(bool) return bool
  
  let len = s1.length;
  // Iterate through s2, subtract for new characters and add for old characters
  // Since we subtracted before, we add them back later. If there is an anagram, the map will be all 0
  for(let i = len; i < s2.length; i++){
    let val = s2[i];
    if(!map[val]) map[val] = 0
    map[val]--
    map[s2[i - len]]++

    const bool = everyZero(map)
    if(bool) return bool
  }
  return false
}
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.