[C language] Two types of problems with judging substrings

Use the last c[a[i]-'a']++; this method counts the number of occurrences of the string from 0 to 26, and then loops from 0 to 26 to see the size of the two arrays at a specific position Whether they are consistent can complete the first problem.
The second problem is that because the substring can be exchanged but other characters cannot be added in between, first store the first one in the first way, and then loop the second one every n (the length of the substring) every time. Create new arrays, new loops, new comparisons. As long as there is a different number of letters, it will jump out, which means that the substring does not meet the conditions, and continue to traverse downward. If all 26 are looped, it means that it is a substring.

1.
The characters in the middle of the substring can be exchanged and can also contain other characters. For
example, abdccba contains ac.

#include<stdio.h>
#include<string.h>
main(){
    
    
    char a[99],b[99];

 gets(a);

 gets(b);

 int i,j,n,m,flag=0;

 int c[26]={
    
    0};

 int d[26]={
    
    0};

 n=strlen(a);

 m=strlen(b);

 for(i=0;i<n;i++)

 {
    
    

          c[a[i]-'a']++;

  } 

  for(i=0;i<m;i++)

  {
    
    

         d[b[i]-'a']++;

  }

  for(i=0;i<26;i++)

 {
    
    

          if(c[i]!=d[i]&&c[i] != 0)

          {
    
    

          printf("Flase");

          return 0;  

          }

 }

 printf("yes");

 }

2. The middle character of s2 can be exchanged but cannot contain other characters

Insert picture description here`

#include<stdio.h>
#include<string.h>
main(){
    
    
char a[99],b[99];
          gets(a);
          gets(b);

         int i,n,m;
         int c[26]={
    
    0};
         n=strlen(a);
         m=strlen(b);
         for( i=0; i<n; i++)
         {
    
    
                  c[a[i]-'a']++;
          } 
            for (i = 0; i <= (m - n); i++) {
    
           
            int d[26] = {
    
    0};
            int j;
            for(j = i; j < n+i; j++)

          {
    
    

                 d[b[j]-'a']++;

          }//遍历建立s2中长度为len(s1)的子串

             for (j = 0; j < 26; j++) {
    
    
           
           if (c[j] != d[j] ) {
    
    

                break; // 只要有一个字母的个数不同就跳出,代表改子串不符合条件,继续向下遍历           
}       
}       
           if (j == 26) {
    
    
           printf("Yes");
           return 0; 
}
}
           printf("None"); //遍历完所有子串都不行
}

Guess you like

Origin blog.csdn.net/m0_46110288/article/details/106029643