View Code of Problem 2591

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

int main(){ 
    int t;
    scanf("%d",&t);
    while(t--){
        char str1[1005];
        char str2[1005];
        char ans[1005];int k=0;
        int alg[200]={0};
        scanf("%s",str1);
        scanf("%s",str2);
        for(int i=0;i<strlen(str1);i++){
            alg[str1[i]]++;
        }
        for(int i=0;i<strlen(str2);i++){
            if(alg[str2[i]]!=0){
                ans[k++]=str2[i];
                alg[str2[i]]--;
            }
        }
        for(int i=k-1;i>0;i--){
            int flag=0;
            for(int j=0;j<i;j++){
                if(ans[j]>ans[j+1]){
                    char tmp;
                    tmp=ans[j];
                    ans[j]=ans[j+1];
                    ans[j+1]=tmp;
                    flag=1;
                }
            }
            if(flag==0){
                break;
            }
        }
        for(int i=0;i<k;i++){
            printf("%c",ans[i]);
        }
        if(k==0){
            printf("-1");
        }
        printf("\n");
    }
	return 0;
}

Double click to view unformatted code.


Back to problem 2591