สร้างอาร์เรย์ใหม่ที่มีความยาว 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