• Prefix and Suffix


    题目描述

    Snuke is interested in strings that satisfy the following conditions:

    The length of the string is at least N.
    The first N characters equal to the string s.
    The last N characters equal to the string t.
    Find the length of the shortest string that satisfies the conditions.

    Constraints
    1≤N≤100
    The lengths of s and t are both N.
    s and t consist of lowercase English letters.

    输入

    The input is given from Standard Input in the following format:

    N
    s
    t

    输出

    Print the length of the shortest string that satisfies the conditions.

    样例输入

    3
    abc
    cde
    

    样例输出

    5
    

    提示

    The shortest string is 'abcde'.

    #include <bits/stdc++.h>
    
    using namespace std;
    int main(){
        ios::sync_with_stdio(false);
        int len;
        string a,b;
        cin>>len;
        cin>>a>>b;
        int i,j,sum=len*2,ans=len*2;
        i=len-1,j=len-1;
        while(j>=0&&i>=0)
        {
            if(a[i]==b[j]){
                i--;
                j--;
                sum--;
            }
            else if(a[i]!=b[j]&&i!=len-1){
                i=len-1;
                sum=len*2;
            }
            else if(a[i]!=b[j]&&i==len-1){
                j--;
                sum=len*2;
            }
        }
        i=len-1,j=len-1;
        swap(a,b);
        while(j>=0&&i>=0)
        {
            if(a[i]==b[j]){
                i--;
                j--;
                ans--;
            }
            else if(a[i]!=b[j]&&i!=len-1){
                i=len-1;
                ans=len*2;
            }
            else if(a[i]!=b[j]&&i==len-1){
                j--;
                ans=len*2;
            }
        }
        cout<<min(ans,sum)<<endl;
    }
    View Code

    这道题刚开始就WA了一大片

    这个不能天真的以为b接在a后面

    还有天天吃小白菜的代码真的太乱了

    今天亲自敲了一下

    不要忘记努力,不要辜负自己 欢迎指正 QQ:1468580561
  • 相关阅读:
    继承
    反射
    DOS使用笔记
    [LeetCode] Merge Intervals
    [LeetCode] Insert Interval
    [LeetCode] Permutation Sequence
    [LeetCode] Rotate List
    [LeetCode] Text Justification
    [LeetCode] Simplify Path(可以不用看)
    [LeetCode] Edit Distance(很好的DP)
  • 原文地址:https://www.cnblogs.com/smallocean/p/8821257.html
Copyright © 2020-2023  润新知