题目
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);
}
}在这里插入代码片