아이공의 AI 공부 도전기

[Baekjoon] 1152번 단어의 개수 (C++)

 

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

 

1152번: 단어의 개수

첫 줄에 영어 대소문자와 공백으로 이루어진 문자열이 주어진다. 이 문자열의 길이는 1,000,000을 넘지 않는다. 단어는 공백 한 개로 구분되며, 공백이 연속해서 나오는 경우는 없다. 또한 문자열

www.acmicpc.net

 

     

C++

방법 1 - 4916KB, 40ms, 298B

 

#include <iostream>
#include <string>
using namespace std;
int main() {
	int i, cnt=0;
	bool c = false;
	string str;
	getline(cin, str);
	
	for (i=0; i<str.length(); i++){		
		if (str[i] == ' '){
			c = false;						
		}
		else if (!c) {			
				c = true;
				cnt++;
		}			
	}
	cout << cnt << endl;
}

초기 시도한 방법 : string을 활용한 방법, getline을 통해 문자열을 입력 받음.

 

bool을 이용하여 공백일 때 false로 만들고 공백이 아닐 때는 true로 바꿔서 글자 하나하나 확인해나가며 보는 방법

 

공백 : bool c = false

공백이 아닌 알파벳일 때 c = false라면 바로 이전이 공백이었다는 의미, 이 때 cnt 숫자 하나 증가

공백이 아닌 알파벳일 때 c = true라면 바로 이전이 알파벳이었다는 의미, 이 때는 무시

 

방법 2 - 3680KB, 8ms, 326B

#include <iostream>
#include <string>
using namespace std;
int main() {
	cin.tie(NULL);
	ios::sync_with_stdio(false);		
	int i, cnt=0;
	bool c = false;
	string str;
	getline(cin, str);		
	
	for (i=0; i<str.length(); i++){		
		if (str[i] == ' ') c = false;
		else if (!c) {			
				c = true;
				cnt++;
		}			
	}
	cout << cnt;
}

 

앞 단계에서 배우지만 cin 자체가 느리기 때문에 아래와 같은 코드를 삽입함으로써 속도를 향상시킬 수 있다.

cin.tie(NULL);
ios::sync_with_stdio(false);

 

방법 3 - 2876KB, 8ms, 339B

 

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int main() {
	char str[1000001];
	int i, cnt = 0;
    	cin.tie(NULL);
	ios::sync_with_stdio(false);
	cin.getline(str, 1000001);
	for (i = 0; i < strlen(str); i++) {
		if (str[i] != ' ' && (str[i+1] == ' ' || str[i+1] == NULL)) 
			cnt++;
	}
	printf("%d", cnt);
}

string 대신 char을 활용한 방법

strlen을 사용하기 위해 cstring, cstdio 호출

 

1) i번째가 공백이 아닌 알파벳이고 다음이 공백일 때

2) i번째가 공백이 아닌 알파벳이고 다음이 null일 때

숫자 증가

 

공유하기

facebook twitter kakaoTalk kakaostory naver band
loading