zoukankan      html  css  js  c++  java
  • 索引处的解码字符串

    给定一个编码字符串 S。为了找出解码字符串并将其写入磁带,从编码字符串中每次读取一个字符,并采取以下步骤:

    • 如果所读的字符是字母,则将该字母写在磁带上。
    • 如果所读的字符是数字(例如 d),则整个当前磁带总共会被重复写 d-1 次。

    现在,对于给定的编码字符串 S 和索引 K,查找并返回解码字符串中的第 K 个字母。

    示例 1:

    输入:S = "leet2code3", K = 10
    输出:"o"
    解释:
    解码后的字符串为 "leetleetcodeleetleetcodeleetleetcode"。
    字符串中的第 10 个字母是 "o"。
    

    示例 2:

    输入:S = "ha22", K = 5
    输出:"h"
    解释:
    解码后的字符串为 "hahahaha"。第 5 个字母是 "h"。
    

    示例 3:

    输入:S = "a2345678999999999999999", K = 1
    输出:"a"
    解释:
    解码后的字符串为 "a" 重复 8301530446056247680 次。第 1 个字母是 "a"。

    package com.sigmod;
    class Solution {
    
        public boolean isDigit(char c) {
            if (c >= '0' && c <= '9')
                return true;
            else
                return false;
        }
        public String decodeAtIndex(String S, int K) {
            long si = 0;
            for (int i = 0; i < S.length(); i++) {
                if (isDigit(S.charAt(i)))
                si *= (S.charAt(i) - '0');
                else si++;
            }
            for (int i = S.length() - 1; i >= 0; i--) {
                K %= si;
                if (K == 0 && !isDigit(S.charAt(i))) return ""+S.charAt(i);
                if (isDigit(S.charAt(i))) si /= (S.charAt(i) - '0');
                else si--;
            }
            return "";
        }
    }
    
    public class Loader {
        public static void main(String[] args) {
            Solution sol = new Solution();
            String result = sol.decodeAtIndex("ha22",5);
            System.out.println(result);
        }
    }
  • 相关阅读:
    PAT (Basic Level) Practise 1013 数素数
    PAT (Basic Level) Practise 1014 福尔摩斯的约会
    codeforces 814B.An express train to reveries 解题报告
    KMP算法
    rsync工具
    codeforces 777C.Alyona and Spreadsheet 解题报告
    codeforces 798C.Mike and gcd problem 解题报告
    nginx + tomcat多实例
    MongoDB副本集
    指针的艺术(转载)
  • 原文地址:https://www.cnblogs.com/sigmod3/p/9529290.html
Copyright © 2011-2022 走看看