题解 | #游游的好串#
游游的好串
http://www.nowcoder.com/questionTerminal/7aad9d56acca40d9a7eb64cf6ca3cc0c
核心思路:一个好串的所有前缀串都是好串 比如 0010,它的所有前缀 0、00、001、0010都是好串
所以我们要找计算从i开始的所有最长好串的长度,然后求和就是结果(注意结果要开long)
类似括号匹配,但这里是0的数量大于1的数量(左括号的数量大于右括号的数量)
import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String s = in.next(); int n = s.length(); long res = 0; // 维护一个栈,记录字符串中1出现的位置,当有0时则弹出1 Deque<Integer> st = new ArrayDeque<>(); // ans[i]表示以i为开头最长好串的长度 int[] ans = new int[n]; for(int i = n - 1; i >= 0; i--) { if(s.charAt(i) == '1') { st.push(i); } else { // 一个好串它的所有前缀(下标0开始的子串)也都是好串 ans[i] = st.isEmpty() ? n - i : st.pop() - i; res += ans[i]; } } System.out.println(res); } }