Online Judge | Problem Set | Authors | Online Contests | User | ||||||
---|---|---|---|---|---|---|---|---|---|---|
Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest |
Java解决方案package com.security.gateway; import java.util.Scanner; /** * @author Wanghs * @create 2022/3/10 * @description */ public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String nS = sc.nextLine(); int n = Integer.valueOf(nS); for (int i = 0; i < n; i++) { sc.nextLine(); String dataS = sc.nextLine(); toW(toStr(dataS.split(" "))); } sc.close(); } /** * 将字符串转为w序列,并输出 * @param s 0/1字符串 */ private static void toW(String s) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < s.length(); i++) { if (String.valueOf(s.charAt(i)).equals("1")) { //当为1时,w计数为1,c计数为0 int c = 0; //与当前1匹配的0的距离 int w = 1; //1的个数,遇到0自减,遇到1自增,当为0时,意味着匹配到对应的0了 //以当前索引倒序遍历 for (int k = i - 1; k >= 0; k--) { //当为1时,w计数自增 if (String.valueOf(s.charAt(k)).equals("1")) { w++; } else { //当为0时,w计数自减1,c计数自增 w--; c++; } if (w == 0) //若w为0,则说明已经找到了对应的0了,跳出循环 break; } sb.append(c + " "); } } String s1 = sb.toString(); sb = null; System.out.println(s1.substring(0, s1.length() - 1)); } /** * 翻译成字符串,左括号为"0",右括号为"1" * * @param p p序列 * @return 返回翻译后的字符串 */ private static String toStr(String[] p) { StringBuffer sb = new StringBuffer(); int first = Integer.valueOf(p[0]); appendByNum(sb, first); sb.append("1"); for (int i = 1; i < p.length; i++) { int zeroN = Integer.valueOf(p[i]) - Integer.valueOf(p[i - 1]); if (zeroN > 0) { appendByNum(sb, zeroN); } sb.append("1"); } String s = sb.toString(); sb = null; return s; } /** * 追加多个零 * @param sb 载体 * @param num 零的个数 */ private static void appendByNum(StringBuffer sb, int num) { for (int i = 0; i < num; i++) { sb.append("0"); } } } Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator