[每日一题]90:亲密字符串

83 阅读1分钟

题目描述

给定两个由小写字母构成的字符串 A 和 B ,只要我们可以通过交换 A 中的两个字母得到与 B 相等的结果,就返回 true ;否则返回 false 。

示例 1

输入: A = "ab", B = "ba"
输出: true

示例 2:

输入: A = "ab", B = "ab"
输出: false

示例 3:

输入: A = "aa", B = "aa"
输出: true

示例 4:

输入: A = "aaaaaaabc", B = "aaaaaaacb"
输出: true

示例 5:

输入: A = "", B = "aa"
输出: false

提示:

  • 0 <= A.length <= 20000
  • 0 <= B.length <= 20000
  • A 和 B 仅由小写字母构成。

C++代码示例

#include <iostream>
#include <string>
using namespace std;

bool isBroStr(string s1, string s2) {
	int len1 = s1.size(), len2 = s2.size();
	if (len1 != len2) return false;

	// s1,s2字符串相等的情况下,如果s1里面有相同的元素就为true
	if (s1 == s2) {
		for (int i = 0; i < len1; i++) {
			for (int j = i+1; j < len2; j++) {
				if (s1[i] == s1[j]) {
					return true;
				}
			}
		}
		return false;
	}
	// s1,s2不相等的情况下
	else {
		int tmp, flag = 1;
		for (int i = 0; i < len1; i++) {
			if (s1[i] != s2[i] && flag) {
				tmp = i;
				flag = 0;
			}
			else if (s1[i] != s2[i]) {
				swap(s1[i], s1[tmp]);
				if (s1 == s2)
					return true;
				else
					return false;
			}
		}
	}
	return false;
}

int main() {
	string s1, s2;
	while (cin >> s1 >> s2) {
		bool flag = isBroStr(s1, s2);
		if(flag)
			cout << "true" << endl;
		else
			cout << "false" << endl;
	}
	return 0;
}