알고리즘/삼성 sw 아카데미

15230 알파벳 공부

칼퇴시켜주세요 2022. 11. 4. 19:28
728x90

알파벳 소문자(a-z)로 구성된 문자열 N개가 주어졌을때 문자열을 알파벳을 순서대로 보면서 앞에서부터  개의 알파벳이 순서에 맞게 적혀 있는지 구하는 프로그램이다.

 

각 케이스마다 문자열을 input 이라고 놓았을경우 input[0]은 문자열의 첫번째 문자가 되고 input[1]은 문자열의 두번째 문자가 된다. i=0 부터 current = input[i], next = input[i+1] 에서 next - current 가 항상 1이 나오면 알파벳 순서도 나열되있다고 알 수 있다. 한편 문제에서 "순서는 a부터 순서대로 일치하는 알파벳 개수를 계산하여야 한다". 라는 조건이 있기 때문에 input[0]이 a가 아니면 0을 반환한다.

 

#include<iostream>
using namespace std;
 
int main(int argc, char** argv)
{
    int test_case;
    int T;
     
    cin>>T;
     
    for(test_case = 1; test_case <= T; ++test_case)
    {
 
        string input;
        cin >> input;
        int current = input[0] ;
        int next = input[1];
        if(current != 'a')
        {
            cout << "#" << test_case << " " << 0 << "\n";
        }
        else
        {
            int count = 1;
            for(int i = 1; i < input.size(); i++)
            {
                int isSequntial = next - current;
                if(isSequntial != 1)
                {
                    break;
                }
                if((next - current) == 1)
                {
                    next = input[i + 1];
                    current = input[i];
                    count++;
                }
            }
            cout << "#" << test_case << " " << count << "\n";
        }
    }
    return 0;
}

pass

반응형