푸른 바다 님이 쓰신 글 :
: #include<stdio.h>
:
: main()
: {
: char str[80];
: int i, spaces;
:
: printf("Enter a string");
: gets(str);
:
: spaces=0;
: for(i=0;str[i];i++);
: if(str[i]==' ') spaces++;
:
: printf("Number of spaces: %d", spaces);
: }
:
: 제가 알고 있는 공백 세는 프로그램인데 이 프로그램을 좀더 효율적으로 만들수 있는 방법이 있을 까요? 좋은 방법있으신 분들 리플 부탁드립니다. m(-..-)m m(_.._)m
더 이상 효율적(effective)으로는 만들 수 없습니다.
문자열의 길이가 N일때, 수행 시간은 N에 비례하는 알고리듬입니다.(이것을 O(N)으로 표기합니다.)
ANSI C++의 문자열 타입인 string과, count 알고리듬을 사용하면 한 줄로도 쓸 수 있습니다.
int main()
{
using namespace std;
cout << "Enter a string";
string str;
getline(cin, str);
int spaces = count(str.begin(), str.end(), ' ');
cout << "Number of spaces: " << spaces << endl;
}
그러나 역시 수행 시간은 O(N)으로, 효율성은 동일합니다.
|