[leetcode - Bliend-75 ] 242. Valid Anagram (Easy)

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

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.

给定两个 string, s 和 t,如果 s 和 t 用到的 chart 数量一样则回传 true 反之回传 false,一样利用 hash-table 分别纪录两个 string 中 chart 出现的次数,最后将两个 hash-table 的内容作比较即可。

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Input: s = "rat", t = "car"
Output: false

Coding

var isAnagram = function(s, t) {  if (s.length !== t.length) return false  const sObj = {}, tObj = {};  s.split('').forEach(s => {    if (!sObj[s]) {      sObj[s] = 1;    } else {      sObj[s]++;    }  })  t.split('').forEach(t => {    if (!tObj[t]) {      tObj[t] = 1;    } else {      tObj[t]++;    }  })  for (const key in sObj) {    if (Object.hasOwnProperty.call(sObj, key)) {      if (!tObj[key]) return false;      if (sObj[key] !== tObj[key]) return false;    }  }  return true;};

hash-table 的 get 为 O(1) 而 for-loop 两个 string 的遍历为 O(2n) -> O(n)

Time complexity: O(n)Space complexity: O(n)

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章