There is now a string s consisting of only numbers and lowercase letters.
If the string s is interesting, then s must be split into several substrings, each substring satisfies the beginning of the number, and the number represents the number of characters after it. For example, s = “4g12y6hunter”, we can divide it into “4g12y” and “6hunter”, so the string is interesting.
If s is an interesting string, output “yes”, otherwise output “no”
class Solution {
public:
/**
* @param s: the string s
* @return: check if the string is interesting
*/
string check(string &s) {
// Write your code here
int sLength = s.length();
if (sLength == 0) {
return “no”;
}
queue<int> q;
q.push(0);
int idx, n, num, nextIdx;
while (q.size() > 0) {
// pop front
int idx = q.front();
q.pop();
n = 0;
for (; idx < sLength; idx++) {
num = s[idx] - (int)'0';
if (num < 0 || num > 9) {
break;
}
n = n*10 + num;
// 从当前位置向后跳过 n 个字符
// 并且检查下一个字符是否为数字或者恰好结束
nextIdx = idx + n + 1;
if (nextIdx > sLength) {
break;
} else if (nextIdx == sLength) {
// 当前位置恰好结束
return "yes";
} else if (nextIdx != idx) {
// push back
q.push(nextIdx);
}
}
}
return "no";
}