如何使用 C# 在不使用内置函数的情况下返回第一个唯一字符?

创建一个长度为 256 的空新数组,逐个字符遍历整个字符串并递增新数组中的值。最后遍历整个数组并返回值为 1 的第一个字符。

示例 1

aabccd -→2 1 2 1 → 返回计数为 1 的第一个字符。即 b 通过与 ascii 值相减。

示例 2

using System;
namespace ConsoleApplication{
   public class Arrays{
      public char ReturnCharacterOfFirstUniqueCharachter(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 s[index];
      }
   }
   class Program{
      static void Main(string[] args){
         Arrays a = new Arrays();
         Console.WriteLine(a.ReturnCharacterOfFirstUniqueCharachter("bbookisgreat"));
         Console.ReadLine();
      }
   }
}
输出结果
k

猜你喜欢