관리 메뉴

기억을 위한 기록들

[Code Wars] Duplicate Encoder(C++) 본문

Etc..

[Code Wars] Duplicate Encoder(C++)

에드윈H 2024. 2. 5. 20:07

https://www.codewars.com/kata/54b42f9314d9229fd6000d9c/train/cpp

 

Codewars - Achieve mastery through coding practice and developer mentorship

A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

 

문제는 다음과 같다.

 

The goal of this exercise is to convert a string to a new string where each character in the new string is "("  if that character appears only once in the original string, or ")" if that character appears more than once in the original string.

이 연습의 목표는 문자열을 새 문자열에 있는 각 문자가 원래 문자열에 한 번만 나타나는 경우 "(", 또는 원래 문자열에 두 번 이상 나타나는 경우 ")"인 새 문자열로 변환하는 것입니다.

Ignore capitalization when determining if a character is a duplicate.

문자가 중복인지 확인할 때 대문자를 무시합니다.

 

capitalization  - 대문자 

 

ex)

 

요약하자면 중복이 없다면 ( 문자를 쓰고, 중복이 있는 문자라면 )를 넣어서 결과를 보여주는 것이다.

 

내 풀이 : 

#include <string>
#include <map>
std::string duplicate_encoder(const std::string& word){    
  std::map<char,int> m;  
  
  //대소문자 구분하지 않아 | 연산자를 이용해
  // map에다가 갯수를 카운트 했다.
  for(const auto item:word)
  {
    m[item|32]+=1;  
  }
  
  
  std::string s;
  for(const auto item:word)
  {
  	//카운트한 문자가 한개라면 ( 를 넣고
    if(m[item|32]==1) 
    {
      s+="(";
    }else //아니라면  ) 를 넣었다
    {
      s+=")";  
    }
  }
  
  return s;
}

 

 

Best Practice을 받은 다른 사람 풀이 :

로직 자체는 크게 다르진 않지만, 보고 든 생각은 if else인 경우와 if 조건이 간결하다면 삼항이 좋은 것 같다.

#include <string>
#include <cctype>

std::string duplicate_encoder(const std::string& word){

    std::map<char, int> table;
    for(auto x : word) table[std::tolower(x)]++;
    
    std::string result;
    for(auto x: word) result += (table[std::tolower(x)]==1)? "(":")";
    
    return result;
}