1. 程式人生 > >添加字符--全國模擬(三)

添加字符--全國模擬(三)

思路 namespace max brush 開頭 res == stream clas

[編程題] 添加字符

時間限制:1秒 空間限制:32768K 牛牛手裏有一個字符串A,羊羊的手裏有一個字符串B,B的長度大於等於A,所以牛牛想把A串變得和B串一樣長,這樣羊羊就願意和牛牛一起玩了。 而且A的長度增加到和B串一樣長的時候,對應的每一位相等的越多,羊羊就越喜歡。比如"abc"和"abd"對應相等的位數為2,為前兩位。 牛牛可以在A的開頭或者結尾添加任意字符,使得長度和B一樣。現在問牛牛對A串添加完字符之後,不相等的位數最少有多少位? 輸入描述: 第一行為字符串A,第二行為字符串B,A的場地小於等於B的長度,B的長度小於等於50.字符均為小寫字母。 輸出描述: 輸出一個整數表示A串添加完字符之後,不相等的位數最少有多少位? 輸入例子: abe cabc 輸出例子: 1 解題思路:本題是采用暴力搜索的方法。 針對a字符串,讓它的首位分別與b的0位到n2-n1位對其,進行比較,求出最大的位相等數目,然後不等數目 = n2 - (n2-n1+result) 個 例如:abc 與 topabcoder abc topabcoder 相等數目為0 abc topabcoder 相等數目為0 abc topabcoder 相等數目為0 abc topabcoder 相等數目為3 abc topabcoder 相等數目為0 abc topabcoder 相等數目為0 abc topabcoder 相等數目為0 abc topabcoder 相等數目為0 因此result = 3 count = n2 - (n2-n1+result) = 10 - (10-3+3) =0 即abc 變為topabcoder正好與b相同 註意點:兩字符串相等情況需要單獨進行處理,直接按位比較,輸出n2-相等數目即可。
#include <iostream>
#include <string.h>
using namespace std;
 
int main()
{
    string a;
    string b;
    while(cin>>a>>b)
    {
        int equal = 0;
 
        int result = 0;
 
        int count = 0;
        int n1 = a.size();
        int n2 = b.size();
         
        if(n1 == n2)
        {
            for(int i=0;i<n1;i++)
            {
                if(a[i] != b[i])
                {
                    count++;
                }
            }
            cout<<count<<endl;
        }
        else
        {
            for(int i=0;i<=n2-n1;i++)
            {
                int k = i;
                for(int j=0;j<n1;j++)
                {
                    if(b[k] == a[j])
                    {
                      
                        equal++;
                    }
                    k++;
                }
                result = max(result,equal);
                equal=0;
            }
            count = n2 - (result + (n2 - n1));
            cout<<count<<endl;
 
 
        }
    }
}

  

添加字符--全國模擬(三)