【LeetCode】761 Special Binary String
题干:
Special binary strings are binary strings with the following two properties:
- The number of 0’s is equal to the number of 1’s.
- Every prefix of the binary string has at least as many 1’s as 0’s.
Given a special string S, a move consists of choosing two consecutive, non-empty, special substrings of S, and swapping them.(Two strings are consecutive if the last character of the first string is exactly one index before the first character of the second string.)
At the end of any number of moves, what is the lexicographically largest resulting string possible?
Note:
- S has length at most 50.
- S is guaranteed to be a special binary string as defined above.
题目分析:
- 特殊二进制串中1和0的数目相等
- 在二进制串中的任意一个前缀中,1的数量肯定大于等于0的数量
第2点可以说是解题的关键,在满足第一个条件的情况下,该二进制串第一位肯定是1,最后一位肯定是0。否则就不满足第二点要求;比如说有字符串"0101"
,该字符串满足第一点要求,但是并不满足第二点要求;
代码
/*
* 1、找到满足要求的特殊二进制串,该二进制串肯定是以1开始,以0结束,
* 所以除去最前面的1和最后面的0,中间部分也是特殊二进制串,继续对中间部分进行递归处理。
* 2、将找到的满足要求的特殊二进制串放入list中,然后按照字典序进行排序。
* 3、返回进行字典序排序的结果
* @param S
* @return
*/
public String makeLargestSpecial(String S) {
//如果count==0,说明到当前位置为止,0和1的数量相同
int count = 0;
int i = 0;
//用来存储当前特殊二进制字符串
List<String> list = new ArrayList<String>();
for(int j = 0; j < S.length(); j++) {
if(S.charAt(j) == '1')
count++;
else
count--;
if(count == 0) {//找到了符合要求的特殊二进制字符串
//体现了第二点要求
list.add("1" + makeLargestSpecial(S.substring(i+1,j)) + "0");
i = j + 1;
}
}
//对当前找到的特殊二进制字符串进行字典序排序
Collections.sort(list,Collections.reverseOrder());
return String.join("",list);
}