如何使用 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP