算法-字符串c#

給定一個字符串,請你將字符串重新編碼,將連續的字符替換成“連續出現的個數+字符”。比如字符串AAAABCCDAA會被編碼成4A1B2C1D2A。

輸入描述:
每個測試輸入包含1個測試用例
每個測試用例輸入只有一行字符串,字符串只包括大寫英文字母,長度不超過10000。

輸出描述:
輸出編碼後的字符串

輸入例子1:
AAAABCCDAA

輸出例子1:
4A1B2C1D2A

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp5
{
    class Program
    {
        static void Main(string[] args)
        {
            string str1 = Console.ReadLine();
            int j = 1;
            for(int i = 0; i < str1.Length-1; i++)
            {
                if (str1[i+1] == str1[i]) { j++; }
                else
                {
                    Console.Write(j +""+ str1[i]);
                    j = 1;
                }
                
            }
            Console.Write(j+""+str1[str1.Length - 1]);
            Console.WriteLine();
            Console.ReadKey();
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章