1) 문제 분석
워드에서 단어 수 보여주는 것처럼 띄어쓰기를 기준으로 그냥 단어가 몇 개 있는지 세는 간단한 문제이다. 처음에는 문제를 대충 읽어서 중복 단어는 세지 않는 걸로 이해하고 set을 사용해서 중복 단어를 제외하고 그랬는데 틀려서 다시 보니까 반대였다..ㅎㅎ 이렇게 되면 문자열 앞과 뒤에 공백이 있을 수 있다는 점만 조심하면 쉽게 풀리는 문제인 것 같다.
처음 시도에는 c++의 string 타입과 입출력으로 getline,cout을 사용했는데, 36ms 정도의 속도가 나왔다. C의 stdio를 이용하면 속도가 더 빨라질 것 같아서 string 대신에 char 배열을 잡고 fgets로 입력 받은 다음에 결과를 printf로 출력해주었더니 같은 알고리즘이어도 8ms라는 더 빠른 속도가 나왔다.
2) 코드
1. C 코드
#include <stdio.h>
using namespace std;
int main(){
//input string
char buf[1000001];
//true if a new word was found
bool ch;
//true if a space was found
bool space;
//total number of words
int count=0;
//get a line from user and save it in buf
fgets(buf, sizeof(buf), stdin);
//count total number of words
//each word is separated by a space
//the input string might begin/end with some spaces
ch = false; space = true;
for(int i=0; buf[i]!='\n' && buf[i] != '\0'; i++){
if(buf[i]==' ' && ch){ //buf[i] is a space and there has been a constant stream of characters
//a new word
count++;
//set the flags
ch = false;
space = true;
}
else if(buf[i]!=' ' && space){ //buf[i] is the first character of new word
ch = true; space = false;
}
}
//check if the last word wasn't counted
if(ch)
count ++;
//print out the total number of words
printf("%d",count);
}
C++ 코드
#include <iostream>
using namespace std;
int main(){
string buf;
bool ch;
int count;
bool space;
buf.reserve(1000001);
getline(cin, buf);
ch = false; space = true;
count = 0;
for(int i=0; buf[i]!='\0'; i++){
if(buf[i]==' ' && ch){
count++;
ch = false;
space = true;
}
else if(buf[i]!=' ' && space){
ch = true; space = false;
}
}
if(ch)
count ++;
cout << count;
}