문자열(String)

백준 1152번: 단어의 개수

cepiloth 2018. 6. 27. 20:21
반응형

https://www.acmicpc.net/problem/1152


1. 문제

영어 대소문자와 띄어쓰기만으로 이루어진 문장이 주어진다. 이 문장에는 몇 개의 단어가 있을까? 이를 구하는 프로그램을 작성하시오.


2. 알고리즘

키워드 - 문자열


3. 코드


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include<stdio.h>    
main() {
    int  i;
    char s[1000001= { };
    int count = 0,butt=1;
 
    gets(s);    
 
    for (i = 0; i < sizeof(s); i++)
        if (i == && s[i] == 0break;
        else if (i==&& s[i] != 0continue;
        else if (s[i-1]!=' ' && s[i] == ' ') count++;
        else if (s[i] == 0) {
            count++;
            if (s[i - 1== ' ') count--;
            break;
        }
    printf("%d\n", count);
}
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
#include <sstream>
#include <string>
#include <algorithm>
#include <functional>
#include <vector>
#include <list>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <stack>
#include <cstring>
using namespace std;
 
#define MAX_SIZE 100
#define INF 0x7fffffff
 
long long dp[1000001];
/*
* @memory  - 1996 kb
* @time    - 36 ms
*/
int main() {
 
    cin.tie(0);
    std::ios::sync_with_stdio(false);
 
    string s; //cin >> s;
    getline(cin, s);
    bool prvAlpha = false;
    int sol = 0;
    for (int i = 0; i < s.size(); ++i) {
        char ch = s[i];
        ch = tolower(ch);
        if (ch >= 'a' && ch <= 'z'){
            if (prvAlpha == false) {
                sol++;
                prvAlpha = true;
            }
        } else
            prvAlpha = false;
    }
    
    cout << sol << "\n";
    return 0;
}
 
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <iostream>
#include <sstream>
#include <string>
#include <algorithm>
#include <functional>
#include <vector>
#include <list>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <stack>
#include <cstring>
using namespace std;
 
#define MAX_SIZE 100
#define INF 0x7fffffff
 
long long dp[1000001];
/*
* @memory  - 11460 kb
* @time    - 8 ms
*/
int main() {
 
    cin.tie(0);
    std::ios::sync_with_stdio(false);
 
    string s; //cin >> s;
    getline(cin, s);
    const int size = s.size();
    int count = 0;
    bool prevAlpha = false;
    
    // 공백을 세지말고 알파뱃을 셉시다 
    for(int i=0; i<size; i++) {
 
        if (isalpha(s[i])) {
            if (prevAlpha == false) {
                count++;
                prevAlpha = true;
            }            
        } else {
            prevAlpha = false;
        }
    }
 
    cout << count << "\n";
    return 0;
}
 
cs


반응형