Notice
Recent Posts
Recent Comments
Link
«   2025/06   »
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
Archives
Today
Total
관리 메뉴

hwooo

프로그래머스 (C/C++) 120894 : 영어가 싫어요 본문

Study/Algorithm

프로그래머스 (C/C++) 120894 : 영어가 싫어요

hwooo 2023. 7. 7. 00:21

https://school.programmers.co.kr/learn/courses/30/lessons/120894

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr


풀이

처음 문자에 따라 경우를 나눠 숫자를 인식하고, 이를 하나씩 answer에 더하는 방식으로 구현했다.

그런데 다른 사람의 풀이를 보니 replace 함수를 사용해서 풀이한 게 더 깔끔해서 나도 그 방식으로 해보았다.

 

replace란?

 

c++ 문자열 일부 교체하기(replace)

#include #include using namespace std; int main() { string sentence = "i like coding"; string find_str = "coding"; string replace_str = "history"; sentence.replace(sentence.find(find_str), find_str.length(), replace_str); cout

popawaw.tistory.com

 

참고한 풀이

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr


코드 1

#include <string>
#include <vector>

using namespace std;

long long solution(string numbers) {
    long long answer = 0;
    int i=0, add=0;
    while(i<numbers.size()){
        if(numbers[i]=='o'){
            add=1, i+=3;
        }
        else if(numbers[i]=='t'){
            if(numbers[i+1]=='w') add=2, i+=3;
            else add=3, i+=5;
        }
        else if(numbers[i]=='f'){
            if(numbers[i+1]=='o') add=4;
            else add=5;
            i+=4;
        }
        else if(numbers[i]=='s'){
            if(numbers[i+1]=='i') add=6, i+=3;
            else add=7, i+=5;
        }
        else if(numbers[i]=='e') add=8, i+=5;
        else if(numbers[i]=='n') add=9, i+=4;
        else if(numbers[i]=='z') add=0, i+=4;
        
        answer=answer*10+add;
    }
    return answer;
}

코드2 (replace 사용)

#include <string>
#include <vector>

using namespace std;

long long solution(string numbers) {
    long long answer = 0;
    
    vector<string> Find_str = { "zero", "one", "two", "three", "four", "five",
        "six", "seven", "eight", "nine"};
    
    for(int i = 0; i < 10; i++){
        if(numbers.find(Find_str[i]) == string::npos) continue;
        while(numbers.find(Find_str[i]) != string::npos)
            numbers.replace(numbers.find(Find_str[i]), Find_str[i].size(), to_string(i));
    }
    answer = stoll(numbers);
    return answer;
}