Leetcode每日一题 20230927 Decoded String at Index

文章介绍了两种方法解决Java中处理长字符串时的内存溢出问题,一是逐字符检查并构建新StringBuilder,二是找出重复循环字符串缩短解码长度。
摘要由CSDN通过智能技术生成

题目链接 定位

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:

  1. 方便转换char ascii的方式 digit - ‘0’, letter - ‘a’ / ‘A’
  2. 要新建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:

  1. 首先求出decoded长度
  2. 从后往前找
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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值