公式

C - Extra Character 解説 by en_translator


One of the answer is the first position when scanning the characters of \(S\) and \(T\) from the beginning.

Sample code (C++):

#include<bits/stdc++.h>
using namespace std;

int main(){
	string S,T;
	cin >> S >> T;
	
	for(int i=0;i<S.size();i++){
		if(S[i]!=T[i]){
			cout << i+1 << endl;
			return 0;
		}
	}
	cout << N+1 << endl;
}

The algorithm can be justified as follows.

Let us denote by \(S_i\) and \(T_i\) the \(i\)-th characters of \(S\) and \(T\), respectively.
The problem is equivalent to: “which character of \(T\) should you remove to make it equal \(S\)?”
Let \(p\) be the minimum \(i\) such that \(S_i\neq T_i\).

  • The removed character cannot be later than the \(p\)-th character (because the \(p\)-th character remains different.)
  • Suppose that the removed character is the \(q\)-th one, prior to the \(p\)-th. Then, the correspondence of the latter characters of \(S\) and \(T\) determined by \(q\) is equivalent to that of \(p\), so \(p\) is also the answer.

Therefore, the algorithm was justified.