본문 바로가기
백준

백준 8595 히든 넘버

by 콩순이냉장고 2021. 8. 22.

문제 URL : https://www.acmicpc.net/problem/8595

 

8595번: 히든 넘버

첫째 줄에 단어의 길이 n (1 ≤ n ≤ 5,000,000)이 주어진다. 둘째 줄에는 단어가 주어진다. 단어는 알파벳 대/소문자와 숫자(0-9)로 이루어져 있다. 

www.acmicpc.net

 

문제접근법 : 푸는방식은 따로설명드리지 않을게요

정규표현식과 그렇지 단순히 숫자만 찾는 알고리즘을 비교하는 코드를 보여드리겠습니다.

하지만 정규표현식도 어떻게 쓰냐에따라 시간이 차이가 나는것을 비교해드리려합니다.

 

소스코드 : 

정규표현식1(시간초과 코드)

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
31
//By 콩순이냉장고
#include <bits/stdc++.h>
using namespace std;
string s;
void input() {
    int n;
    cin >> n;
    cin >> s;
}
void solve() {
    regex re(R"(\d+)");
    auto it = sregex_iterator(s.begin(), s.end(), re);
    long long res = 0;
    smatch match;
    while (regex_search(s, match, re)) {
        res += stoll(match[0]);
        s = match.suffix();
    }
    cout << res << "\n";
 
}
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    //freopen("input.txt", "r", stdin);
    input();
    solve();
}
 
 
cs

 

정규표현식 2번(iterator를 이용한 search코드)

 

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
//By 콩순이냉장고
#include <bits/stdc++.h>
using namespace std;
string s;
void input() {
    int n;
    cin >> n;
    cin >> s;
}
void solve() {
    regex re(R"(\d+)");
    auto it = sregex_iterator(s.begin(), s.end(), re);
    long long res = 0;
    while (it != sregex_iterator()) {
        res += stoll(it->str());
        it++;
    }
    cout << res << "\n";
 
}
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    //freopen("input.txt", "r", stdin);
    input();
    solve();
}
 
 
cs

 

 

단순구현 코드:

 

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
31
32
33
34
//By 콩순이냉장고
#include <bits/stdc++.h>
using namespace std;
string s;
void input() {
    int n;
    cin >> n;
    cin >> s;
}
void solve() {
    long long res = 0;
    string num;
    for (int i = 0; i <= s.size(); i++) {
        if ('0' <= s[i] && s[i] <= '9') {
            num += s[i];
        }
        else {
            if (num.empty())continue;
            res += stoll(num);
            num = "";
        }
    }
    cout << res << "\n";
}
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    //freopen("input.txt", "r", stdin);
    input();
    solve();
}
 
 
cs

 

단순구현이 당현 빠르겠지만 클린코드측면으로 보자면 정규표현식이 매우 깔끔한것같네요

또한 정규표현식을 어떻게 사용하냐에따라 스피드도 결정하니 잘생각해서 사용하시는게 좋을것같습니다.

 

궁금한점 혹은 모르는점 어떤질문이든 댓글은 언제나 환영입니다.

 

 

'백준' 카테고리의 다른 글

백준 17267 상남자  (0) 2021.08.26
백준 1942 디지털 시계  (0) 2021.08.23
백준 22351 수학은 체육과목 입니다3  (0) 2021.08.22
백준 13505 두 수 XOR  (0) 2021.08.22
백준 14906 스러피  (0) 2021.08.19