-
9. [Programmers] 알고리즘 문제풀기 Java script 문자열 다루기 기본Algorithm 2022. 12. 20. 23:53728x90
두 시간을 잡고있었던 문제..
최대한 다른 사람들의 답안을 먼저 보지 않고 내가 아는 방법만으로 해결해보고싶은 오기때문에 한참 고민했다.
우선 내가 이번 문제에 써보고 싶었던 method들이 있었다
1. 삼항연산자
2. &&와 || 논리연산자
첫 번째 시도 & 두 번째 시도
function solution(s) { var answer = false; Array.from(s).includes('a'||'b'||'c'||'d'||'e'||'f'||'g'||'h'||'i'||'j'||'k'||'l'||'m'||'n'||'o'||'p'||'q'||'r'||'s'||'t'||'u'||'v'||'w'||'x'||'y'||'z')? answerA="alphabetincluded" : answerA="notincluded" if (answerA==="notincluded" && s.length===4||s.length===6) { return true; } else if(answerA==="alphabetincluded") { return false; } return answer }
function solution(s) { var answer = ''; let answerA =''; answerA+=Array.from(s).includes('a'||'b'||'c'||'d'||'e'||'f'||'g'||'h'||'i'||'j'||'k'||'l'||'m'||'n'||'o'||'p'||'q'||'r'||'s'||'t'||'u'||'v'||'w'||'x'||'y'||'z')? "alphabetincluded" : "notincluded" if (answerA==="notincluded"){ if (s.length==4||s.length==6) { answer= true; } } else { answer= false; } return answer }
숫자만 포함되어있는지 판단할 메서드를 이용하면 편했겠지만 우선 내가 알고있는 메서드만 이용해보고싶었다.
그래서 시작된 노가다...
a부터 z까지, 그리고 대문자로도 A부터 Z까지를 모두 논리합연산자 || 를 이용해서 포함여부를 확인해봤다 ....
확실히 효율성이 떨어지는 방법이었지만,
그렇게해서 먼저 alphabetincuded와 notincluded로 구분하는 것 까진 성공했다
그리고 처음으로 삼항연산자를 이용해보았다!!!
그래서 notincluded인 경우에 length가 4 혹은 6인 케이스만 true, 나머지는 모두 false로 값을 도출해보려했으나,
어디서 꼬인건지 자꾸만 모든 값이 true로 나오거나 알파벳이 포함되어도 숫자 length가 4혹은 6이면 true로 나오는 불상사가 벌어졌다.
우리 팀 분들께서 열심히 틀린부분 고쳐주려고 같이 봐주셨다. 그렇게 점점 답에는 가까워지는가했지만 결국 실패한 코드..
그래도 우리 팀원분들께 항상 많이 배운다 ㅠㅠ
그렇게 결국 찾게된 답
function solution(s) { if (s.length !== 4 && s.length !== 6) return false; for (let i = 0; i < s.length; i++) { if (isNaN(Number(s[i]))) return false; } return true; }
1. 먼저 알파벳 숫자 상관 없이 length가 4와 6이 아닌 경우는 false로 떨궈버리고,
(여기서 &&논리곱연산자를 이용한 이유는 4가 아니면서 6또한 아닌 케이스를 false로 떨구기 위해서이다!)
2. for문을 이용해서 isNaN 메서드를 이용했다.
(s[i]) 배열 s내의 요소들을 먼저 넘버화시키고 (알파벳이 섞여있으면 자료형이 number가 안되겠죵?) isNaN 메서드를 통해 숫자형이 맞는지 판단하여 숫자형이 맞는 경우에만 true를 도출
다른 분들은 어떻게 풀었는지 너무너무 궁금했던 문제..
앞으론 혼자 고집부리면서 너무 시간 끌지 말고 새로운 메서드들을 적극적으로 검색해보고 활용을 해야겠다!
그래도 머리 쥐어뜯으며 고생해보면서 하루하루 실력이 조금씩 늘고있는 것이 느껴진다
나를 한층 성장시킨 문제 문자열다루기 기본!!!
728x90'Algorithm' 카테고리의 다른 글
알고리즘 하드코딩 장인 [프로그래머스] 약수의 개수와 덧셈 (코드 간결화) (0) 2023.04.11 HackerRank 문제 해석, 풀이 Plus Minus- Java script (0) 2023.04.06 [알고리즘풀기] 프로그래머스 로그인성공? (0) 2023.03.30 [알고리즘풀기] 프로그래머스 문자열 나누기 Java script (0) 2023.03.28 10.[Programmers]알고리즘 문제 Java script 2016 요일구하기 (사서 고생하는 사람의 노가다 구경하실래요?) (0) 2022.12.21