创建一个长度为 256 的空新数组,逐个字符遍历整个字符串并递增新数组中的值。最后遍历整个数组并返回值为 1 的第一个字符。
aabccd -→2 1 2 1 → 返回计数为 1 的第一个字符。即 b 通过与 ascii 值相减。
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