解题思路
这道题要求计算满足条件的排列方式数量,关键点是:
- 每个字母代表一种颜色
- 相邻砖块颜色不能相同
- 排列方式相同的定义是:颜色序列相同
- 需要找到最多只有一对不同颜色相邻的排列方式数量
解题步骤:
- 统计字符串中不同字符的数量
- 如果字符种类超过2个,输出0(因为必然会有多于一对不同颜色相邻)
- 如果只有1种字符,输出1(只有一种排列方式)
- 如果有2种字符,输出2(可以从两端开始排列,得到两种不同的排列)
代码
#include <iostream>
#include <string>
#include <set>
using namespace std;
int main() {
string s;
cin >> s;
// 使用set统计不同字符的数量
set<char> chars;
for(char c : s) {
chars.insert(c);
}
// 根据不同字符数量判断结果
if(chars.size() > 2) {
cout << 0 << endl; // 超过2种颜色必然有多对不同颜色相邻
} else if(chars.size() == 2) {
cout << 2 << endl; // 2种颜色可以有两种排列方式
} else {
cout << 1 << endl; // 1种颜色只有一种排列方式
}
return 0;
}
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.next();
// 使用HashSet统计不同字符的数量
Set<Character> chars = new HashSet<>();
for(char c : s.toCharArray()) {
chars.add(c);
}
// 根据不同字符数量判断结果
if(chars.size() > 2) {
System.out.println(0); // 超过2种颜色必然有多对不同颜色相邻
} else if(chars.size() == 2) {
System.out.println(2); // 2种颜色可以有两种排列方式
} else {
System.out.println(1); // 1种颜色只有一种排列方式
}
}
}
s = input()
# 使用set统计不同字符的数量
chars = set(s)
# 根据不同字符数量判断结果
if len(chars) > 2:
print(0) # 超过2种颜色必然有多对不同颜色相邻
elif len(chars) == 2:
print(2) # 2种颜色可以有两种排列方式
else:
print(1) # 1种颜色只有一种排列方式
算法及复杂度
- 算法:使用集合统计不同字符数量。
- 时间复杂度:
,其中
是字符串长度。
- 空间复杂度:
,最多存储
个不同的字符。