23-06-25 계륵 일기

E woo·2023년 6월 25일

계륵 일기

목록 보기
2/31
post-thumbnail

파이썬식, C 언어식

또 파이썬과 C 언어로 문제를 풀고 답을 구글에서 비교해보니 확실히 스타일이 다른 것들을 볼 수 있다.

#include <iostream>
#include <string>

using namespace std;

int main()
{
    int N;
    string str;
    cin >> N;
    cin >> str;

    int sum = 0;
    for (int i = 0; i < N; i++)
    {
        sum += str[i] - '0';
    }
    cout << sum;

    return 0;
}
n = input()

print(sum(map(int,input())))

파이썬 split() 와 split(" ") 의 차이점

파이썬에서 split(" ") 와 split() 은 차이를 가진다.

str = "abc    d"

print(str.split())
print(str.split(" "))

split() 은 모든 공백을 1개로 처리하지만
split(" ") 은 공백을 따로 처리하게 된다.
공백이 연속적으로 나올 경우 일반 문자 다음에 오는 공백을 제외한
나머지 공백을 각각 리스트에 하나의 요소로 따로 처리한다.

그래서 4개의 공백이 있으므로 공백 3개는 따로 리스트에 저장되었다.


C++ 공백 제거

문자열의 공백을 기준으로 몇 개의 단어가 문자열에 있는지 단어의 개수를 구하는 문제에서
https://www.acmicpc.net/problem/1152

문자열의 시작에 공백이 있을 경우에 대해서도 처리해야 된다.

입력 문자열 : " The first character is a blank"
-> 맨 앞에 공백이 있음

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main()
{
    string S;
    getline(cin, S);

    istringstream iss(S);

    string token;
    int cnt = 0;

    while (iss >> token)
    {
        cnt += 1;
    }

    cout << cnt;

    return 0;
}

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main()
{
    string S;
    getline(cin, S);

    // if (S[0] == ' ')
    // {
        // S.erase(0, 1);
    // }

    istringstream iss(S);

    string token;
    int cnt = 0;

    while (getline(iss, token, ' '))
    {
        cnt += 1;
    }

    cout << cnt;

    return 0;
}

getline 을 사용할 경우 문자열의 맨 처음 공백에 대해서 처리하지 못하여 cnt 가 하나가 더 증가된다.

(아마 위에서 본 split() 과 split(" ") 의 차이와 같은 맥락이지 않을까... 싶다)


코드 비교

올바른 괄호 문제로 본 내 코드와 다른 사람 코드 비교
https://school.programmers.co.kr/learn/courses/30/lessons/12909

  • 내 코드
#include <string>
#include <iostream>
#include <stack>

using namespace std;

bool solution(string s)
{
    bool answer = true;
    
    stack<char> my_s;
    
    for(int i = 0; i < s.length(); i++)
    {
        if (my_s.size() == 0 && s[i] == ')')
        {
            cout << "0";
            return 0;
        }
        if (s[i] == '(')
        {
            my_s.push(s[i]);
        }
        else if (s[i] == ')')
        {
            my_s.pop();
        }
    }
    
    if (my_s.size() == 0)
        answer = true;
    else
        answer = false;
    // [실행] 버튼을 누르면 출력 값을 볼 수 있습니다.
    cout << "Hello Cpp" << endl;

    return answer;
}
  • 다른 사람의 코드
#include<string>
#include <iostream>

using namespace std;

bool solution(string s)
{
    int n = 0;
    for (int i = 0; i < s.length(); i++) {
        if (n < 0)
            return false;
        if (s[i] == '(')
            n++;
        else if (s[i] == ')')
            n--;
    }
    return n == 0;
}

전에 백준에서 한번 풀어봤던 것 같은데 스택을 이용하느라 ')' 처리 부분의 stack 이 empty 일 때의 처리가 거슬렸지만,

다른 사람의 코드를 보니 굳이 자료구조를 사용하지 않고 매우 간단하게 구현할 수 있었다.

(너무 관념에 얽매이지 말고 무엇이 최선일지도 생각해보자.)

profile
뒘벼

0개의 댓글