![[백준 1152번] 단어의 개수 (c)](https://img1.daumcdn.net/thumb/R750x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FUpaPx%2FbtrpTg5zyVR%2Fi1X6DYfeRREboJkncLtC50%2Fimg.png)
[백준 1152번] 단어의 개수 (c)알고리즘2022. 1. 5. 23:22
Table of Contents
문제
https://www.acmicpc.net/problem/1152
1152번: 단어의 개수
첫 줄에 영어 대소문자와 공백으로 이루어진 문자열이 주어진다. 이 문자열의 길이는 1,000,000을 넘지 않는다. 단어는 공백 한 개로 구분되며, 공백이 연속해서 나오는 경우는 없다. 또한 문자열
www.acmicpc.net
코드 1
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <ctype.h> //isspace()가 정의된 헤더파일
#include <string.h> //strlen()가 정의된 헤더파일
int main(void)
{
int cnt = 0; //단어 개수를 세는 변수
char str[1000001];
int lastIndex; //입력된 str의 마지막 인덱스
gets_s(str, sizeof(str)); //공백을 포함한 문자열을 입력받음
lastIndex = strlen(str) - 1; //배열의 index는 0부터 시작이니까
for (int i = 0; i < strlen(str); i++) { //i < strlen(str)을 str[i] != '\0'로 변경가능
if (isspace(str[i])) cnt++; //isspace를 안쓰고 str[i] == ' '로 변경가능
}
if (isspace(str[0]) && isspace(str[lastIndex])) cnt--; //젤 앞, 끝 모두 공백
if (!(isspace(str[0])) && !(isspace(str[lastIndex]))) cnt++; //젤 앞, 끝 모두 공백X
printf("%d", cnt);
return 0;
}
회색 사각형을 입력된 공백으로 생각하고 아래 표를 봐주세요.
세번째 열을 참고하여 line18에서 cnt--를, line19에서 cnt++를 해주었습니다.
코드 2
#include<stdio.h>
#include <string.h> //strlen()가 정의된 헤더파일
int main(void)
{
char str[1000001];
int cnt = 0; //cnt는 단어의 개수
gets(str);
for (int i = 0; i < strlen(str); i++) { //i < strlen(str)을 str[i] != '\0'로 변경가능
if (str[i] == ' ' && str[i + 1] != '\0') cnt++; //ctype.h를 추가하고 isspace(str[0])으로 변경가능
}
if (str[0] == ' ') printf("%d", cnt);
else printf("%d", cnt + 1);
}
공백이 나왔을 때, 그 공백 다음 문자가 '\0'이 아닌 경우를 조건으로 추가했습니다.(line10)
따라서 이 방법은 첫번째 방법과 달리, 애초에 마지막 문자가 공백일 경우를 제외하고 cnt를 계산했습니다. (마지막 문자가 공백일 경우, 그 다음 문자가 '\0')
이제 제일 앞 문자가 공백인지 아닌지만 판단하고, 그에 따른 연산을 진행하면 됩니다.
'알고리즘' 카테고리의 다른 글
[백준 1193번] 분수찾기 (c) (0) | 2022.01.07 |
---|---|
[백준 2775번] 부녀회장이 될테야 (c) (0) | 2022.01.06 |
[백준 1157번] 단어공부 (c) (0) | 2022.01.04 |
[백준 10809번] 알파벳 찾기 (c) (0) | 2022.01.03 |
[백준 1110번] 더하기 사이클 (C) (0) | 2022.01.02 |
@blog_bbg :: bbg
포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!