|
@@ -0,0 +1,75 @@
|
|
|
|
|
+package leetcode.p1980;
|
|
|
|
|
+
|
|
|
|
|
+import java.util.HashSet;
|
|
|
|
|
+import java.util.Objects;
|
|
|
|
|
+import java.util.Set;
|
|
|
|
|
+
|
|
|
|
|
+/**
|
|
|
|
|
+ * @ProjectName: LeetCode
|
|
|
|
|
+ * @FileName: Solution
|
|
|
|
|
+ * @Author: 杨逸
|
|
|
|
|
+ * @Data:2026/3/8 14:52
|
|
|
|
|
+ * @Description: https://leetcode.cn/problems/find-unique-binary-string/
|
|
|
|
|
+ * 1980. 找出不同的二进制字符串
|
|
|
|
|
+ */
|
|
|
|
|
+public class Solution {
|
|
|
|
|
+
|
|
|
|
|
+ public String findDifferentBinaryString(String[] nums) {
|
|
|
|
|
+ return hashSolution(nums);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ private String binaryString2intSolution(String[] nums){
|
|
|
|
|
+ /**
|
|
|
|
|
+ * 灵神的方法1
|
|
|
|
|
+ * 因为n最大为16,所有可以将二进制字符串转为int
|
|
|
|
|
+ * 然后遍历int,判断是否出现
|
|
|
|
|
+ */
|
|
|
|
|
+ Set<Integer> set =new HashSet<>();
|
|
|
|
|
+ for (String num : nums) {
|
|
|
|
|
+ set.add(Integer.parseInt(num,2));
|
|
|
|
|
+ }
|
|
|
|
|
+ int ans = 0;
|
|
|
|
|
+ while (true){
|
|
|
|
|
+ if (!set.contains(ans)) {
|
|
|
|
|
+ break;
|
|
|
|
|
+ }
|
|
|
|
|
+ ans++;
|
|
|
|
|
+ }
|
|
|
|
|
+ String binaryString = Integer.toBinaryString(ans);
|
|
|
|
|
+ return "0".repeat(set.size() - binaryString.length()) + binaryString;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ private Set<String> set = new HashSet<>();
|
|
|
|
|
+ private char[] ans;
|
|
|
|
|
+ /**
|
|
|
|
|
+ * 回溯枚举字符串,哈希判断是否出现
|
|
|
|
|
+ * @param nums
|
|
|
|
|
+ * @return
|
|
|
|
|
+ */
|
|
|
|
|
+ private String hashSolution(String[] nums){
|
|
|
|
|
+ ans = new char[nums.length];
|
|
|
|
|
+ for (String num : nums) {
|
|
|
|
|
+ set.add(num);
|
|
|
|
|
+ }
|
|
|
|
|
+ return dfs(nums,0);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ private String dfs(String[] nums,int index) {
|
|
|
|
|
+ if (index >= nums.length){
|
|
|
|
|
+ String temp = new String(ans);
|
|
|
|
|
+ if (!set.contains(temp)){
|
|
|
|
|
+ return temp;
|
|
|
|
|
+ }
|
|
|
|
|
+ return null;
|
|
|
|
|
+ }
|
|
|
|
|
+ //取0
|
|
|
|
|
+ ans[index] = '0';
|
|
|
|
|
+ String dfs = dfs(nums, index + 1);
|
|
|
|
|
+ if(Objects.nonNull(dfs)){
|
|
|
|
|
+ return dfs;
|
|
|
|
|
+ }
|
|
|
|
|
+ //取1
|
|
|
|
|
+ ans[index] = '1';
|
|
|
|
|
+ return dfs(nums, index + 1);
|
|
|
|
|
+ }
|
|
|
|
|
+}
|