본문 바로가기
Study/Algorithm

[Algorithm - 문자열] 공통문자열 찾기

by Hoony-Daddy 2023. 8. 29.
728x90

N개 문자열 중에 공통된 문자열 찾기

/******************************************************************************

                              Online C++ Compiler.
               Code, Compile, Run and Debug C++ program online.
Write your code in this editor and press "Run" button to compile and execute it.

*******************************************************************************/

#include <iostream>
#include <vector>
#include <cstdio>
#include <string>
using namespace std;

int main()
{
    int n;
    std::cin>>n;
    std::vector<std::string> words;
    for(int i=0;i<n;i++){
        std::string word;
        std::cin>>word;
        words.push_back(word);
    }
   
    std::string common_word = words[0];
    int common_index = 100;
    for(int i=1;i<n;i++){
        int length = min(common_word.length(),words[i].length());
        for(int j=0;j<length;j++){
            if(common_word[j]!=words[i][j] and j<common_index){
                common_index=j-1;
            }
            else if(j==length-1 and j<common_index){
                 common_index=j;
            }
        }
    }
    printf("%d\n",common_index);
    std::cout<<common_word.substr(0,common_index+1);
   
    

    return 0;
}