Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

หาตัวอักษรลำดับที่ K หลังถอดรหัสสตริงใน C++


คำอธิบายโจทย์

สตริงเข้ารหัส: ตัวอักษรตามด้วยตัวเลข = repeat (เช่น "ab2c3" = "ababccc") หาตัวอักษรตำแหน่ง K (1-indexed) โดยไม่ต้อง decode ทั้ง string

ตัวอย่าง

s="ab2c3", k=5 → Output: 'c'

Decoded: a b a b c c c → ตำแหน่ง 5 คือ 'c'

วิธีแก้ปัญหา

Recursive + Length Tracking:

  • อ่านตัวอักษร: total_len++, ถ้า ==k คืนตัวอักษรนั้น
  • อ่านตัวเลข n: next_total_len = total_len * n
  • ถ้า k ≤ next_total_len: pos = k % total_len (0→total_len) เรียก recursive หา pos
  • ไม่ใช่: total_len = next_total_len อ่านต่อ

โค้ดตัวอย่าง

#include <cstdlib>
#include <iostream>
using namespace std;

char findKthChar(string s, int k) {
    int len = s.length(), i=0, total_len=0;
    while(i < len) {
        if(isalpha(s[i])) {
            total_len++;
            if(total_len == k) return s[i];
            i++;
        } else {
            int n=0;
            while(i

ผลลัพธ์

c