Double-ended Strings

Double-ended Strings Codeforces-1506C

2021.05.01 训练题D
**题目大意:**给定一组(两行)字符串,两个字符串可以进行操作:从头部删除字符或者从尾部删除字符,找到最终两个字符串相等时删除的最小字符数
**做题思路:**这道题考察两个字符串的最长公共子串,串的长度为20,可以暴力破解,将短的字符串分解成所有字串,然后在长串中找是否有,取长度最长的情况即可
题目:

You are given the strings a and b, consisting of lowercase Latin letters. You can do any number of the following operations in any order:

if |a|>0 (the length of the string a is greater than zero), delete the first character of the string a, that is, replace a with a2a3…an;
if |a|>0, delete the last character of the string a, that is, replace a with a1a2…an−1;
if |b|>0 (the length of the string b is greater than zero), delete the first character of the string b, that is, replace b with b2b3…bn;
if |b|>0, delete the last character of the string b, that is, replace b with b1b2…bn−1.
Note that after each of the operations, the string a or b may become empty.

For example, if a="hello" and b="icpc", then you can apply the following sequence of operations:

delete the first character of the string a ⇒ a="ello" and b="icpc";
delete the first character of the string b ⇒ a="ello" and b="cpc";
delete the first character of the string b ⇒ a="ello" and b="pc";
delete the last character of the string a ⇒ a="ell" and b="pc";
delete the last character of the string b ⇒ a="ell" and b="p".
For the given strings a and b, find the minimum number of operations for which you can make the strings a and b equal. Note that empty strings are also equal.

Input
The first line contains a single integer t (1≤t≤100). Then t test cases follow.

The first line of each test case contains the string a (1≤|a|≤20), consisting of lowercase Latin letters.

The second line of each test case contains the string b (1≤|b|≤20), consisting of lowercase Latin letters.

Output
For each test case, output the minimum number of operations that can make the strings a and b equal.

Example
Input
5
a
a
abcd
bc
hello
codeforces
hello
helo
dhjakjsnasjhfksafasd
adjsnasjhfksvdafdser
Output
0
2
13
3
20

代码实现:


import java.util.Scanner;

public class Double_ended_Strings {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int t = sc.nextInt();
		sc.nextLine();
		while(t-- != 0) {
			String s1 = sc.nextLine();
			String s2 = sc.nextLine();
			int ans ;
			if(s1.length() >= s2.length()) ans = getAns(s1,s2);
			else ans = getAns(s2,s1);//默认s1为长串,s2为短串
			System.out.println(s1.length()+s2.length()-2*ans);//总长度-两倍公共子串的长度
		}
	}

	private static int getAns(String s1, String s2) {
		String str;
		int maxLen = 0;
		for(int i=0;i<s2.length();i++) {
			for(int j=i+1;j<s2.length()+1;j++) {
				str = s2.substring(i, j);
				if(str.length() <= maxLen) continue;//如果字串长度小于当前最长的情况直接退出,避免了不必要的判断,节省时间
				if(s1.indexOf(str) != -1) maxLen = Math.max(maxLen, str.length());
			}
		}
		return maxLen;
	}
}
上一篇:安卓02作业 -显示学生信息


下一篇:linux中的strings命令