第一行输入一个整数
表示字符串及排列的长度。
第二行输入一个长度为
,仅由
和
构成的字符串
。
如果不存在满足条件的排列,直接输出
;否则,在一行上输出
个整数
表示你构造出的排列。
如果存在多个满足条件的排列,输出任意一个均可,系统将自动判定其正确性。请注意,自测运行功能可能因此返回错误结果,请自行检查答案正确性。
3 001
3 1 2
对于这个样例,
由于
,排列的前一项元素无法构成一个排列;
由于
,排列的前两项元素无法构成一个排列;
由于
,排列的前三项元素构成一个排列;
同时,输出
、
等答案也都是合法的。
4 1110
-1
在此样例中,若存在合法排列,则前三位必须依次形成排列,但第四位又要求整体不形成排列,显然不可能,因此答案为。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); // 读取字符串长度
String s = sc.next(); // 读取01字符串
sc.close(); // 关闭扫描器
// 若字符串最后一位不是1,直接输出-1(无法满足置换要求)
if (s.charAt(n - 1) != '1') {
System.out.println(-1);
return;
}
int flag = 0; // 标记下一个置换区间的起始位置
int[] arr = new int[n]; // 存储置换结果的数组
// 遍历字符串,处理每个'1'对应的置换
for (int i = 0; i < n; i++) {
if (s.charAt(i) == '1') {
// '0'对应的位置:值=自身索引+1(不置换)
for (int j = flag + 1; j < i; j++) {
arr[j] = j + 1;
}
// '1'对应的位置:flag和i互换(值=对方索引+1)
arr[flag] = i + 1;
arr[i] = flag + 1;
flag = i + 1; // 更新下一个置换区间起点
}
}
// 输出最终置换结果
for (int a : arr) {
System.out.print(a + " ");
}
}
}
控制台传过来的字符串为str,①无结果:当str的结尾为0时,说明不可能有满足题意的字符顺序,直接输出-1。
②有结果:遇到1时再填充字符,两层for循环,外层right从前到后寻找字符“1”,
内层j从上一个字符“1”后开始遍历到外层找到的1,填充为j + 2(下标比当前位置靠后。比如第二个位置,我们输入3),
遍历到达“1”(right)时,输出left + 1的值,再把left赋值为right + 1。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextInt()) {
int lens = in.nextInt();
in.nextLine();
String str = in.nextLine();
char[] chars = str.toCharArray();
if (chars[chars.length - 1] == '0'){
System.out.println(-1);
}else{
int impossible = 2;
int possible = 1;
int left = 0;
for (int right = 0; right < chars.length; right++){
if (chars[right] == '1'){
for (int j = left; j < right; j++){
System.out.print(j + 2 + " ");
}
System.out.print(left + 1 + " ");
left = right + 1;
}
}
}
}
}
}
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();
Stack<Integer> st=new Stack<Integer>();
if(s.charAt(n-1)=='0'){
System.out.print(-1);
return;
}
for(int i=1;i<=n;i++){
st.push(i);
if(s.charAt(i-1)!='0'){
while(!st.empty()) System.out.print(st.pop()+" ");
}
}
}
} public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String length = in.nextLine();
String input = in.nextLine();
resultList = new LinkedList<>();
boolean res = getResult(input);
if (res) {
resultList.forEach(s->System.out.print(s + " "));
} else {
System.out.println(-1);
}
}
static List<Integer> resultList = new LinkedList<>();
public static boolean getResult(String str) {
if (str.endsWith("0")) {
return false;
}
Integer temp = 1;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '0') {
resultList.add(i + 2);
} else {
resultList.add(temp);
temp = i + 2;
}
}
return true;
}