题解 | 小红的排列构造 - 找规律 + 模拟
小红的排列构造
https://www.nowcoder.com/practice/a4ec29e74aaa450aa8a4200fe3b06308
import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); String S = in.next(); char[] s = S.toCharArray(); // 末尾为0的字符串肯定是无解的 if (s[n - 1] == '0') { System.out.println("-1"); return; } List<Integer> ans = new ArrayList<>(); int pre = 1; // 这里需要设置成1,有可能是001,最终需要补充1 for (int i = 1; i <= n; i++) { if (s[i - 1] == '0') { ans.add(i + 1); // pre表示当前缺失的元素,比如0101,遍历到第一个1时,pre = 1需要补充1;遍历到第二个1的时候,pre=3,需要补充3; // 对于001的情况,最后需要补充的是第一0所对应的数字1 if(i - 2 >= 0 && s[i - 2] != '0') { pre = i; } } else { // 遇到连续的1或者第一个为1的话,就补充当前位置的数字 if((i - 2 >= 0 && s[i - 2] == '1') || i == 1) { ans.add(i); } else { // 否则补充之前缺失的pre ans.add(pre); } } } for(int i = 0; i < n; i++) { if(i < n - 1) { System.out.print(ans.get(i) + " "); } else { System.out.print(ans.get(i)); } } } }