lintcode 3647 · 迭代压缩字符串【simple 算法 系统设计】

题目

https://www.lintcode.com/problem/3647/description

在本题中,你需要设计一个压缩字符串迭代器。

这个迭代器类需要包含一个构造函数用于接收压缩字符串。

压缩字符串:由若干对字符+数字组成。每对组合中的数字表示为该字符在此处出现的次数。
例如:"a1b2c3" 表示的原字符串为 "abbccc"。

你还需要设计其中的 next()hasNext()两个方法。其方法定义如下:

next():获取原字符串下一个字符
hasNext() 判断原字符串是否存在下一个字符
字符后面的数字一定大于 0。

字符串仅包含大小写字符,数字。

如果调用 next() 函数时不存在字符,则返回 '#'。

样例
样例 1

输入:

"a1b1"
next()
hasNext()
next()
hasNext()
输出:

'a'
true
'b'
false
解释:

压缩字符串 "a1b1" 表示的原字符串为 "ab"。因此调用第一次 next() 时获取到第一个字符 'a',且下一个字符存在且为 'b',因此第一个 hasNext() 返回 true。

而第二次 next() 访问的则是最后一个字符 'b',此时再调用 hasNext() 时已经没有下一个字符了,因此返回 false。

样例 2

输入:

"a1b2c3"
next()
next()
next()
next()
next()
next()
hasNext()
输出:

'a'
'b'
'b'
'c'
'c'
'c'
false
样例 3

输入:

"L1i1n1t1C1o1d1e1"
next()
next()
next()
next()
hasNext()
next()
next()
next()
next()
hasNext()
输出:

'L'
'i'
'n'
't'
true
public class Solution {
     int pos = 0; //当前走到字符的哪个位置了【字符位置非数字位置】
        int nextpos; //下一个字符位置
        String str; //字符串
        int cnt; //当前pos对应字符的个数

        public Solution(String compressedStr) {
            str = compressedStr;
            int start = 1;
            cnt = 0;
            while (start < str.length() && str.charAt(start) >= '0' && str.charAt(start) <= '9') {
                cnt = cnt * 10 + (str.charAt(start) - '0');
                start++;
            }
            nextpos = start;
        }

        public char next() {
            if(!hasNext()) return '#';
            if (cnt > 0) {
                cnt--;
                return (char) str.charAt(pos);
            }

            if (cnt == 0) {
                pos = nextpos;
                int start = pos + 1;
                //System.out.println(start);
                while (start < str.length() && str.charAt(start) >= '0' && str.charAt(start) <= '9') {
                    cnt = cnt * 10 + (str.charAt(start) - '0');
                    start++;
                }
                nextpos = start;
            }
            cnt--;
            return (char) str.charAt(pos);
        }

        public boolean hasNext() {
            return !(nextpos == str.length()&&cnt==0);
        }
}在这里插入代码片
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

赵长辉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值