classSolution { public List<String> validStrings(int n) { List<String> ans = newArrayList<>(); intmask= (1 << n) - 1; for (inti=0; i < (1 << n); i++) { intx= i ^ mask; if ((x & (x >> 1)) == 0) { ans.add(Integer.toBinaryString((1 << n) | i).substring(1)); // 往n位“带有前导0的二进制”的前面加个1,再去掉 } } return ans; } }
Python
1 2 3 4 5 6 7 8 9 10 11
from typing importList
classSolution: defvalidStrings(self, n: int) -> List[str]: ans = [] mask = (1 << n) - 1 for i inrange(1 << n): x = i ^ mask ifnot x & (x >> 1): ans.append(f'{i:0{n}b}') return ans