题解 | 小红的排列构造 (构造解法)
小红的排列构造
https://www.nowcoder.com/practice/a4ec29e74aaa450aa8a4200fe3b06308
思路就是维护一个全局数字 k 初始为 1。遇到字符串里有 '1' 就倒序遍历填充并让 k++
如 00101, 第一次遇到 '1' 答案数组变成 3 2 1 0 0, 第二次遇到 '1' 变成 3 2 1 5 4
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 int n = sc.nextInt(); String s = sc.next(); int cnt1 = 0, idx = -1; if (s.charAt(n - 1) != '1') { System.out.println(-1); return; } int[] ans = new int[n]; int k = 1; for (int i = 0; i < n; i++) { if (s.charAt(i) == '1') { for (int j = i; j >= 0; j--) { if (ans[j] == 0) { ans[j] = k++; } else { break; } } } } for (int i = 0; i < n; i++) { System.out.print(ans[i]); System.out.print(' '); } } }