c++문제풀이

문제

예전에는 운영체제에서 크로아티아 알파벳을 입력할 수가 없었다. 따라서, 다음과 같이 크로아티아 알파벳을 변경해서 입력했다.

크로아티아 알파벳 변경
č c=
ć c-
dz=
đ d-
lj lj
nj nj
š s=
ž z=

예를 들어, ljes=njak은 크로아티아 알파벳 6개(lj, e, š, nj, a, k)로 이루어져 있다. 단어가 주어졌을 때, 몇 개의 크로아티아 알파벳으로 이루어져 있는지 출력한다.

dž는 무조건 하나의 알파벳으로 쓰이고, d와 ž가 분리된 것으로 보지 않는다. lj와 nj도 마찬가지이다. 위 목록에 없는 알파벳은 한 글자씩 센다.

입력

첫째 줄에 최대 100글자의 단어가 주어진다. 알파벳 소문자와 ‘-‘, ‘=’로만 이루어져 있다.

단어는 크로아티아 알파벳으로 이루어져 있다. 문제 설명의 표에 나와있는 알파벳은 변경된 형태로 입력된다.

출력

입력으로 주어진 단어가 몇 개의 크로아티아 알파벳으로 이루어져 있는지 출력한다.

  • 제출 코드
#include <iostream>
#include <cstdio>

int main()
{
	char str[102];
	scanf("%s",str);
	
	int count = 0;
	for(int i = 0; str[i]; ++i)
	{
		if(str[i] != '=' && str[i] != '-'){
			if(str[i] == 'd' && str[i+1] == 'z' && str[i+2] == '=')
	    	{
	    		i += 2;
	    	}
		    else if( str[i] == 'l'  || str[i] == 'n' )
		    {
		    	if( str[i+1] == 'j')
		    	    i += 1;
		    }    
		    ++count;
		}	
	}
	
	printf("%d", count);
	
	return 0;
}
  • switch문 활용한 코드
#include <iostream>
#include <cstdio>
#include <string>
using namespace std;

int main()
{
	string c_alphabet[8] = {"c=","c-","dz=","d-","lj","nj","s=","z="};

	string input_str;
	cin >> input_str;
	
	int count = 0;
	
	for(int i = 0; i <input_str.size(); ++i)
	{
		switch(input_str[i])
		{
			case 'c':
				{
					if(input_str[i+1] == '=')
					{
						++count;
						++i;
						continue;
					}
					else if(input_str[i+1] == '-')
					{
						++count;
						++i;
						continue;
					}						
				}
				break;
			case 'd':
				{
					if(input_str[i+1] == 'z' && input_str[i+2] == '=')
					{
						++count;
						i += 2;
						continue;
					}
					else if(input_str[i+1] == '-')
					{
						++count;
						++i;
						continue;
					}						
				}
				break;
			case 'l':
				{
					if(input_str[i+1] == 'j')
					{
						++count;
						++i;
						continue;
					}						
				}
				break;
			case 'n':
				{
					if(input_str[i+1] == 'j')
					{
						++count;
						++i;
						continue;
					}						
				}
				break;
			case 's':
				{
					if(input_str[i+1] == '=')
					{
						++count;
						++i;
						continue;
					}						
				}
				break;
			case 'z':
				{
					if(input_str[i+1] == '=')
					{
						++count;
						++i;
						continue;
					}						
				}
				break;
		}
		
		if(input_str[i] >= 'a' && input_str[i] <= 'z')
		{
			++count;
		}
		
	}
	printf("%d", count);
	
	return 0;
}
    1. break

      case를 작성할 때는 마지막 부분에서 break로 중단해주어야 해당 case만 실행
      case를 break로 중단하지 않으면 그다음에 있는 case, default가 계속 실행

    1. continue

      continue is used in the scope of loops. A switch is not a loop.
      If the the switch is inside in a loop then you can use continue - the continue command is associated with the loop - not the switch.

c++문제풀이

문제

그룹 단어란 단어에 존재하는 모든 문자에 대해서, 각 문자가 연속해서 나타나는 경우만을 말한다. 예를 들면, ccazzzzbb는 c, a, z, b가 모두 연속해서 나타나고, kin도 k, i, n이 연속해서 나타나기 때문에 그룹 단어이지만, aabbbccb는 b가 떨어져서 나타나기 때문에 그룹 단어가 아니다.

단어 N개를 입력으로 받아 그룹 단어의 개수를 출력하는 프로그램을 작성하시오.

입력

첫째 줄에 단어의 개수 N이 들어온다. N은 100보다 작거나 같은 자연수이다. 둘째 줄부터 N개의 줄에 단어가 들어온다. 단어는 알파벳 소문자로만 되어있고 중복되지 않으며, 길이는 최대 100이다.

출력

첫째 줄에 그룹 단어의 개수를 출력한다.

  • 제출 코드
#include <iostream>
#include <cstdio>
using namespace std;
//1316
 
bool group_checker(char* str); 

int main()
{
	int tc;
	scanf("%d", &tc);
	
    int group_word = 0;
	char input_str[101];
	for(int i = 0; i < tc; ++i)
	{	
	    scanf("%s", input_str);
	    if(group_checker(input_str))
	    ++group_word;
	}
	
	printf("%d\n", group_word);
	return 0;
}

bool group_checker(char* str)
{
	bool checker = true;
	//initialize as false 
	bool word[26] = {false};
	if(str[1] != 0)
	{
		word[str[0] - 'a'] = true;
		
	    for(int i = 1 ; str[i]; ++i)
	    {
		    if(word[str[i] - 'a'] == true)
			    if(str[i-1] != str[i])
				    return false;
				    
	        word[str[i] - 'a'] = true;	
	    }
    }

	if(checker)
		return true;
}

1. find_if() 함수

template<class InputIt, class UnaryPredicate>
constexpr InputIt find_if(InputIt first, InputIt last, UnaryPredicate p)
{
    for (; first != last; ++first) {
        if (p(*first)) {
            return first;
        }
    }
    return last;
} 

algorithm 헤더에 정의 Defined in header "algorithm"
first : 컨테이너의 시작요소
last : 컨테이너의 마지막요소
p : bool 타입의 조건문
[first,last] 범위안의 조건(p)을 만족하는 첫번째 요소를 return

2. find_if() return value

조건을 만족하는 첫 번째 요소 first 를 return
해당 요소가없는 경우 마지막 last 를 return

  • find_if 조건문 이후 컨테이너의 end() 함수와 비교하여 요소를 찾았는지를 비교하는 경우가 있음
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;

int main()
{
    // Create a list of integers with a few initial elements.
    vector<int> number_list;
    number_list.push_back(10);
    number_list.push_back(23);
    number_list.push_back(30);
    number_list.push_back(45);
    number_list.push_back(50);

    // Use the find_if function and a lambda expression to find the
    // first even number in the vector list.
    const vector<int>::const_iterator result =
        find_if(number_list.begin(), number_list.end(),[](int n) { return (n % 2) == 0; });

    // Print the result.
    if (result != number_list.end()) {  //if find_if returns last value, nothing has been found in container
        cout << "The first even number in the list is " << *result << "." << endl;
    } else {
        cout << "The list contains no even number_list." << endl;
    }
}
 

OutPut:
The first even number in the list is 10

  • if (result != number_list.end()) : number_list 내의 컨테이너에서 number_list.end()를 return하면 컨테이너내에서 조건에 맞는 요소를 찾지 못한경우를 의미