题目链接 定位
Method1 intuition 按照要求写出String找
问题: 当生成String过长时会 OutOfMemoryError: Java heap space
class Solution {
public String decodeAtIndex(String s, int k) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++){
if (!Character.isDigit(s.charAt(i))){
sb.append(s.charAt(i));
}
else{
//String num = String.valueOf(s.charAt(i));
//int times = Integer.parseInt(num) - 1;
int times = s.charAt(i) - '0' - 1;
StringBuilder tmp = new StringBuilder();
tmp.append(sb);
for (int j = 0; j < times; j++){
sb.append(tmp);
}
}
}
System.out.println(sb.toString());
return String.valueOf(sb.toString().charAt(k-1));
}
}
Notice:
- 方便转换char ascii的方式 digit - ‘0’, letter - ‘a’ / ‘A’
- 要新建StringBuilder, 不能直接赋原来的sb, 否则原来改现在的也会改
Method2 缩短decoded长度
eg. appleappleappleappleappleapple的第24位和第4位是一样的, 即要找到反复循环的字符串, decoded string would equal some word repeated d times -> index k can be reduced to index k % word.length
Algorithm:
- 首先求出decoded长度
- 从后往前找
class Solution {
public String decodeAtIndex(String s, int k) {
long size = 0;
int decode = s.length();
for (int i = 0; i < decode; i++){
if (Character.isLetter(s.charAt(i))){
size++;
}
else{
size *= (s.charAt(i) - '0');
}
}
for (int i = decode - 1; i >= 0; i--){
k %= size;
if (k == 0 && Character.isLetter(s.charAt(i))){
return String.valueOf(s.charAt(i));
}
if (Character.isDigit(s.charAt(i))){
size /= (s.charAt(i) - '0');
}
else{
size--;
}
}
return null;
}
}