C. Remove Adjacent

C. Remove Adjacent

  1. link

    C. Remove Adjacent

  2. The meaning of problems

    Given a string of length less than 100, erases the adjacent letters Q up to several deleted.

  3. Thinking

    greedy. Each taking a maximum of letters, violence enumeration, time complexity \ (26 * n \)

  4. Code

    #include<bits/stdc++.h>
    using namespace std; 
    string s;
    int n; 
    bool solve()
    {
     for(int j = 26; j >= 1; j--)
         for(int i = 0; i < s.size(); i++)
         {
             if(s[i] != 'a'+j)
                 continue;
             if(i  > 0)
                 if(s[i-1]=='a'+j-1)
                 {
                     s.erase(i,1);
                     return true;
                 }
             if(i  < s.size()-1)
                 if(s[i+1]=='a'+j-1)
                 {
                     s.erase(i,1);
                     return true;
                 }
         }
     return false;
    }
    
    int main(void)
    {
     scanf("%d",&n); 
     cin>>s;
     int ans=0;
     while(solve())
         ans++;
     cout<<ans<<endl;    
    }

Guess you like

Origin www.cnblogs.com/AC-AC/p/12401597.html