Recent Posts
Recent Comments
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags
more
Today
Total
관리 메뉴

고리타분한 개발자

Anagrams 본문

JavaScript/Algorithm

Anagrams

sunlee334 2018. 5. 12. 01:19

목적


나열된 두 개의 문자열이 'anagram'인지 확인하기

'anagram'은 하나의 문자열과 동일한 문자를 사용하는 경우를 말한다.

사용되어진 문자의 갯수도 같아야 한다. 공백이나 기호가 아닌 문자만 관여 되어진다.

대문자는 소문자와 동일하게 간주한다.


example


anagrams('rail safety', 'fairy tales') --> True
anagrams('RAIL! SAFETY!', 'fairy tales') --> True
anagrams('Hi there', 'Bye there') --> False


들어가기에 앞서

const word = 'HI THERE!!!!!'
word.replace(/[^\w]/g, '') // HITHERE
word.replace(/[^\w]/g, '').toLowerCase() // hithere

const obj = {
a: 1,
b: 1,
c: 1
}

Object.keys(obj).length // 3


1.



function anagrams(stringA, stringB) {
const aCharMap = buildCharMap(stringA)
const bCharMap = buildCharMap(stringB)

// stringA의 문자 갯수와 stringB의 문자 갯수가 다를경우 (상단 erMind참고, hello !== hellos)
if (Object.keys(aCharMap).length !== Object.keys(bCharMap).length) {
return false
}
// 두 문자열이 서로 다른 문자로 구성되어 있을경우
for (let char in aCharMap) {
if (aCharMap[char] !== bCharMap[char]) {
return false
}
}

return true
}

function buildCharMap(str) {
const charMap = {}

// 문자만 골라내어서 소문자로 만들기
for (let char of str.replace(/[^\w]/g, '').toLowerCase()) {
charMap[char] = charMap[char] + 1 || 1
}
return charMap
}


2. 


const numbers = [10, 30, 5, -90, 10000]

numbers.sort() // [-90,10,10000,30,5]

const alphabet = ['z', 'd', 'b', 'x', 'r']

alphabet.sort() // ["b", "d", "r", "x", "z"]

const str = 'Hello There!'
const str2 = 'There Hello!'

str
.replace(/[^\w]/g, '')
.toLowerCase()
.split('')
.sort()
.join('') // eeehhllort

str2
.replace(/[^\w]/g, '')
.toLowerCase()
.split('')
.sort()
.join('') // eeehhllort



function anagrams(stringA, stringB) {
cleanString(stringA) === cleanString(stringB)
}

function cleanString(str) {
return str
.replace(/[^\w]/g, '') // 문자만 나오도록
.toLowerCase() // 소문자로 변경
.split('') // 문자로 나누기
.sort() // 문자 정렬
.join('') // 문자열로 합치기
}


'JavaScript > Algorithm' 카테고리의 다른 글

Array Chunking  (0) 2018.05.12
Fizz Buzz  (0) 2018.05.12
Integer Reversal  (0) 2018.05.12
Paldinromes  (0) 2018.05.12
SentenceCapitalization  (0) 2018.05.12
Comments