Codeforces Round #496 (Div. 3) 解题报告 B. Delete from the Left 暴力 模拟

http://codeforces.com/contest/1005/problem/B

解题思路:

1.从左往右匹配的方法:

  • 先令两条串等长(即把长串左边长的部分截掉)
  • 然后两串逐位比较,不相等的话把前面的全部删掉(即都加到cnt)

2.从右往左匹配的方法:

  • 直接两串右往左匹配直到第一次不相等或者两串匹配完毕
  • 两串总长度减去匹配成功的次数×2就是答案

现场写的C++:先找出长串的起始下标,从左向右匹配(当时是真的头大)

#include 
#include 
#include 
#include 
#include 
using namespace std;
const int maxn = 1000 + 10;

int main() {
    string s1,s2;
    cin >> s1 >> s2;
    int i = s1.size() - s2.size();
    i = max(0,i);
    int y = s2.size() - s1.size();
    y = max(0,y);
    int cnt = s1.size() - s2.size();
    cnt = abs(cnt);
    int con = 0;
    for(int k = min(i,y);k < min(s1.size(),s2.size());k++,i++,y++) {
        if(s1[i] == s2[y])
            con++;
        else {
            con++;
            cnt += con * 2;
            con = 0;
        }
    }
    cout << cnt << endl;
    return 0;
}

后期补JAVA:从后往前匹配

import java.util.Scanner;

public class Main {

    public static void main(String args[]) {

        Scanner sc = new Scanner(System.in);
        String s1 = sc.nextLine();
        String s2 = sc.nextLine();
        int cnt = s1.length() + s2.length();
        int x1 = s1.length() - 1,x2 = s2.length() - 1;
        while (x1 >= 0 && x2 >= 0) {
            if(s1.charAt(x1) == s2.charAt(x2)) {
                cnt -= 2;
                x1--;
                x2--;
            } else break;
        }

        System.out.println(cnt);
    }
}


你可能感兴趣的:(codeforces,JAVA)