#P1772. 第3题-相等字符串
-
1000ms
Tried: 160
Accepted: 45
Difficulty: 6
所属公司 :
美团
时间 :2024年3月30日
-
算法标签>思维
第3题-相等字符串
题目思路
思维题,首先肯定可以在2个操作以内让它们相等,即每次选中一个字符串的前缀,转变为相同的那个字符。
考虑如何在一个操作内让它们相等。先找到最长的后缀,假设后缀的起始位置为i,如果s或t的前i-1的前缀都等于一个字符c,那么让另外一个字符串变成这个c即可。
当s就等于t时答案为0。所以对所有情况分类一下即可。
代码
Java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
String t = scanner.nextLine();
int ans = 2;
int n = s.length();
int ok = 0;
int i = n - 1;
while (i >= 0 && s.charAt(i) == t.charAt(i)) {
i--;
}
if (i < 0) {
System.out.println(0);
} else {
int aok = 1, bok = 1;
for (int j = 1; j <= i; j++) {
if (s.charAt(0) != s.charAt(j)) {
aok = 0;
}
if (t.charAt(0) != t.charAt(j)) {
bok = 0;
}
}
if (aok == 1) {
System.out.println("1");
System.out.println("2 " + (i + 1) + " " + s.charAt(0));
} else if (bok == 1) {
System.out.println("1");
System.out.println("1 " + (i + 1) + " " + t.charAt(0));
} else {
System.out.println("2");
System.out.println("1 " + n + " a");
System.out.println("2 " + n + " a");
}
}
}
}
C++
#include <iostream>
#include <string>
using namespace std;
int main() {
string s, t;
cin >> s >> t;
int ans = 2;
int n = s.length();
int ok = 0;
int i = n - 1;
while (i >= 0 && s[i] == t[i]) {
i--;
}
if (i < 0) {
cout << 0 << endl;
} else {
int aok = 1, bok = 1;
for (int j = 1; j <= i; j++) {
if (s[0] != s[j]) {
aok = 0;
}
if (t[0] != t[j]) {
bok = 0;
}
}
if (aok == 1) {
cout << "1" << endl;
cout << "2 " << i + 1 << " " << s[0] << endl;
} else if (bok == 1) {
cout << "1" << endl;
cout << "1 " << i + 1 << " " << t[0] << endl;
} else {
cout << "2" << endl;
cout << "1 " << n << " a" << endl;
cout << "2 " << n << " a" << endl;
}
}
return 0;
}
Python
s = input()
t = input()
ans, n, ok = 2, len(s), 0
i = n - 1
while i >= 0 and s[i] == t[i]:
i -= 1
if i < 0:
print(0)
else:
aok, bok = 1, 1
for j in range(1, i + 1):
if s[0] != s[j]:
aok = 0
if t[0] != t[j]:
bok = 0
if aok:
print("1")
print(f"2 {i + 1} {s[0]}")
elif bok:
print("1")
print(f"1 {i + 1} {t[0]}")
else:
print("2")
print(f"1 {n} a")
print(f"2 {n} a")
会员可通过查看《已通过》的提交记录来查看其他语言哦~
题目描述
小美有两个长度相等的字符串,第一个字符串为 s ,第二个字符串为 t 。
小美每次可以选择一个字符串的一个前缀,然后选择一个字母 c ,将选择的前缀的所有字母都变成 c 。
小美想知道她最少要操作几次可以使得 s 和 t 相等。
输入描述
第一行输入一个长度不超过 105 的字符串s 。
第二行输入一个长度与 s 相等的字符串 t 。
输出描述
第一行输出一个整数m表示答案。
接下来 m 行,每行输出用空格隔开的 i,j,c 表示选择第 i 个字符串的长度为 j 的前缀,将前缀所有字母变成 c 。
样例
输入
aabc
abcc
输出
2
2 3 b
2 2 a
说明
第1次操作选择第2个字符串的长度为3的前缀,将前缀所有字母变成 'b' ,字符串变成 "bbbc" 。
第2次操作选择第2个字符串的长度为2的前缀,将前缀所有字母变成 'a' ,字符串变成 "aabc" 。