Algorithm
You are given two strings s and t. In a single move, you can choose any of two strings and delete the first (that is, the leftmost) character. After a move, the length of the string decreases by 1. You can't choose a string if it is empty.
For example:
- by applying a move to the string "where", the result is the string "here",
- by applying a move to the string "a", the result is an empty string "".
You are required to make two given strings equal using the fewest number of moves. It is possible that, in the end, both strings will be equal to the empty string, and so, are equal to each other. In this case, the answer is obviously the sum of the lengths of the initial strings.
Write a program that finds the minimum number of moves to make two given strings s and t equal.
The first line of the input contains s. In the second line of the input contains t. Both strings consist only of lowercase Latin letters. The number of letters in each string is between 1 and 2⋅105, inclusive.
Output the fewest number of moves required. It is possible that, in the end, both strings will be equal to the empty string, and so, are equal to each other. In this case, the answer is obviously the sum of the lengths of the given strings.
test
west
2
codeforces
yes
9
test
yes
7
b
ab
1
In the first example, you should apply the move once to the first string and apply the move once to the second string. As a result, both strings will be equal to "est".
In the second example, the move should be applied to the string "codeforces" 8 times. As a result, the string becomes "codeforces" → "es". The move should be applied to the string "yes" once. The result is the same string "yes" → "es".
In the third example, you can make the strings equal only by completely deleting them. That is, in the end, both strings will be empty.
In the fourth example, the first character of the second string should be deleted.
Code Examples
#1 Code Example with C++ Programming
Code -
C++ Programming
#include <bits/stdc++.h>
using namespace std;
int main() {
string s, t;
cin >> s >> t;
int res = 0;
for(int i = s.length() - 1, j = t.length() - 1; i >= 0 && j >= 0; --i, --j)
if(s[i] == t[j])
++res;
else
break;
cout << (s.length() - res) + (t.length() - res) << endl;
return 0;
}
Copy The Code &
Try With Live Editor
Input
west
Output
Demonstration
Codeforces Solution-B. Delete from the Left-Solution in C, C++, Java, Python,Delete from the Left,Codeforces Solution