中级农民
- 积分
- 127
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2021-11-29
- 最后登录
- 1970-1-1
|
本楼: |
👍
0% (0)
|
|
0% (0)
👎
|
全局: |
👍 85% (543) |
|
14% (91) 👎 |
注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号
x
1209. Remove All Adjacent Duplicates in String II
原题是 k个字符消掉
变种是任意连续的直接删掉
我code 如下 ,网上抄的, 测试发现有bug- public static String removeAdjDup(String str) {
- // base case
- if (str == null || str.length() == 0) {
- return str;
- }
- char[] chars = str.toCharArray();
- // `k` maintains the index of the next free location in the result,
- // and `i` maintains the current index of the string
- int i, k = 0;
- // start from the second character
- for (i = 1; i < chars.length; i++) {
- // if the current character is not the same as the
- // previous character, add it to the result
- if (chars[i - 1] != chars[i]) {
- chars[k++] = chars[i - 1];
- } else {
- // remove adjacent duplicates
- while (i < chars.length && chars[i - 1] == chars[i]) {
- i++;
- }
- }
- }
- // add the last character to the result
- chars[k++] = chars[i - 1];
- // construct a string with the first `k` chars
- String s = new String(chars).substring(0, k);
- // start again if any duplicate is removed
- if (k != chars.length) {
- return removeAdjDup(s); // Schlemiel painter’s algorithm
- }
- // if the algorithm didn't change the input string, that means
- // all the adjacent duplicates are removed
- return s;
- }
- public static void main(String [] args){
- System.out.print(removeAdjDup( "acbbcaac"));
- }
复制代码 有没有高人帮忙实现下 ,感激不尽
|
上一篇: 加米 lc543. Diameter of Binary Tree 的recursion下一篇: 啥时候算是ready
|