DAY 19 LeetCode学习笔记

【880索引处的解码字符串】

前言

每天早晨第一件事leetcode,不知道啥时候才能熟练点

题目

官方题目

解题

1、本题由于会重复字符串,所以可以巧妙的运用取模操作,通过遍历字符串,当遇到字符时,长度加1,数字时相乘。就可以得到最终的解码字符串长度。
2、对原始字符串进行逆序遍历,每次k%size,分三种情况:

  1. k刚好为0且当前字符为字母,则直接返回
  2. 当前字符为数字,则说明重复的那一段可以直接跳过,size/=c
  3. 或则就将size-1

源码

class Solution {
    public String decodeAtIndex(String S, int K) {
        long size =0;
        for(int i=0;i<S.length();++i){
            char c=S.charAt(i);
            if (Character.isDigit(c)){
                size *= (c-'0');
            }else{
                size+=1;
            }

        }
        for(int i=S.length()-1;i>=0;--i){
            char c = S.charAt(i);
            K %= size;
            if((K==0) &&  Character.isLetter(c)){
                return Character.toString(c);
            }
            if (Character.isDigit(c)){
                size /= c-'0';
            }
            else{
                size-=1;
            }

        }
        throw null;

    }
}
class Solution:
    def decodeAtIndex(self, S: str, K: int) -> str:
        size=0
        for c in S:
            if c.isdigit():
                size *= int(c)
            else:
                size += 1
        for c in reversed(S):
            K %= size
            if K==0 and c.isalpha():
                return c
            if c.isdigit():
                size /= int(c)
            else:
                size -= 1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值