[Leetcode] 1374. Generate a String With Characters That Have Odd Counts

HyeLin·2023년 1월 17일
0
post-thumbnail

Given an integer n, return a string with n characters such that each character in such string occurs an odd number of times.
The returned string must contain only lowercase English letters. If there are multiples valid strings, return any of them.
정수 n이 주어지면 해당 문자열의 각 문자가 홀수 번 발생하도록 n개의 문자가 포함된 문자열을 반환합니다.
반환되는 문자열에는 영문 소문자만 포함되어야 합니다. 유효한 문자열이 여러 개인 경우 해당 문자열 중 하나를 반환합니다.

Ex)

Input: n = 4
Output: "pppz"
Explanation: "pppz" is a valid string since the character 'p' occurs three times and the character 'z' occurs once. Note that there are many other valid strings such as "ohhh" and "love".

💢 실패한 풀이

var generateTheString = function(n) {
 const alpa='abcdefghijklmnopqrstuvwxyz';
  let result=''
  const alpaLength=alpa.length
  
  for(let i=0; i<n;i++){
   result += alpa.charAt(Math.random()*alpaLength)
  }
  
 return result
};

generateTheString(7)

여기까지 했을 때, 랜덤 글자까지 나오고.. 그 후로 그 결과를 가지고 답을 얻을지 고민했다. 그 랜덤 알파벳 글자에서 각 알파벳을 홀수로 바꾸기 부분이 가능할지 의문이었다..
그래서 바꾼 풀이!

성공한 풀이

var generateTheString = function(n) {
    if(n%2 ==1){
  return Array(n).fill('a').join('')
}else{
  return Array(n-1).fill('a').join('') + 'b'
}
  
};

무조건 랜덤 알파벳이 나와야 된다는 생각을 버리고 내가 원하는대로 'a', 'b'로 고정을 했다.
n이 홀수일때는 n의 갯수 만큼 'a'로 채우고, 짝수일 경우에는 한개를 'b'로 채우는 로직으로 변경!

profile
개발자

0개의 댓글