如何使用 C# 返回第一個唯一字元的索引而不使用內建函式?


建立一個長度為 256 的空新陣列,逐個字元遍歷整個字串並增加新陣列中的值。最後遍歷整個陣列並返回值為 1 的第一個字元。

示例 1

aabccd -→2 1 2 1 → 返回第一個計數為 1 的字元。即 b。

示例 2

即時演示

using System;
namespace ConsoleApplication{
   public class Arrays{
      public int ReturnIndexOfFirstUniqueCharachter(string s){
         int index = -1;
         int[] arrayValues = new int[256];
         for (int i = 0; i < s.Length; i++){
            int value = s[i] - 'a';
            arrayValues[value] += 1;
         }
         for (int i = 0; i < s.Length; i++){
            int value = s[i] - 'a';
            if (arrayValues[value] == 1){
               index = i;
               break;
            }
         }
         return index;
      }
   }
   class Program{
      static void Main(string[] args){
         Arrays a = new Arrays();
         Console.WriteLine(a.ReturnIndexOfFirstUniqueCharachter("bookisgreat"));
         Console.ReadLine();
      }
   }
}

輸出

0

已更新於:27-Aug-2021

458 次瀏覽

開啟你的職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.