演算法技巧 字串搜尋 字串中的第乙個唯一字元

2021-10-04 21:48:55 字數 579 閱讀 3720

給定乙個字串,找到它的第乙個不重複的字元,並返回它的索引。如果不存在,則返回 -1。

s = 「leetcode」

返回 0.

s = 「loveleetcode」,

返回 2.

一種方法是使用兩層for迴圈依次取字元,依次往後判斷,結構複雜且費時

第二種方法是使用indexof()和lastindexof()依次獲取每個字元的前後出現的位置,如果兩位置相等則返回索引

可能都會想到第二種方法,但是我還看了大佬的方法,由題可知只會尋找英文小寫字母,所以依次遍歷26個英文本母,獲取其在字串中的位置,不為-1且相等即滿足,在尋找其中的最小值,大幅化簡搜尋次數,固定到26次,精妙無窮,這便是演算法的魅力吧

public

static

intfirstuniqchar

(string s)

if(min==s.

length()

)return-1

;else

return min;

}

字串搜尋

include include include includeusing namespace std char grid 100 100 word 100 int n m int x int y int xx yy void search if k len int main int t cin t ...

字串搜尋

include include include includeusing namespace std char grid 100 100 word 100 int n m int x int y int xx yy void search if k len int main int t cin t ...

《演算法》 字串 字串排序

輸入字串和字串對應的組別 組別也是字串的鍵 在滿足組別有小到大排序的情況下,將字串按字母順序排序 第一步,記錄組別的頻率 為了得到某個字串在排序後的範圍,比如組別2肯定在組別1後面,在組別3前面,把每個組別有多少個人記錄下來,方便我們定位 第三步,分類 該組別的位置起點 向後挪一位 因為當前位被用了...