字符串總結:
1.其實很多數(shù)組填充類的問題,都可以先預先給數(shù)組擴容帶填充后的大小,然后在從后向前進行操作。如題:https://programmercarl.com/%E5%89%91%E6%8C%87Offer05.%E6%9B%BF%E6%8D%A2%E7%A9%BA%E6%A0%BC.html
2.針對數(shù)組中的刪除操作的時候,可以用移除元素的方法原地操作。時間復雜度為O(n):https://programmercarl.com/0027.%E7%A7%BB%E9%99%A4%E5%85%83%E7%B4%A0.html
3.反轉字符串的時候:當需要固定一段一段去處理字符串時,假設長度為k,for循環(huán)可以+k。記?。合日w反轉再局部反轉的思想。或者先局部反轉再整體反轉,可以實現(xiàn)左旋。
28. 找出字符串中第一個匹配項的下標
題目鏈接:https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string/
算法思想:兩重循環(huán)
其實可以用KMP,但是我沒用。
代碼:
class Solution {
public:
? ? bool checksame(string haystack, string needle, int i)
? ? {
? ? ? ? if((i+needle.size())> haystack.size())
? ? ? ? ? ? return false;
? ? ? ? int j=0;
? ? ? ? int max_len = i+needle.size();
? ? ? ? while(i<max_len)
? ? ? ? {? cout<<"i:"<<i<<endl;
? ? ? ? ? ? cout<<"haystack[i]:"<<haystack[i]<<" needle[j]"<<needle[j]<<endl;
? ? ? ? ? ? if(haystack[i]!=needle[j])
? ? ? ? ? ? ? ? return false;
? ? ? ? ? ? i++;
? ? ? ? ? ? j++;
? ? ? ? }
? ? ? ? cout<<"return true"<<endl;
? ? ? ? return true;
? ? }
? ? int strStr(string haystack, string needle) {
? ? ? ? int lenh = haystack.size();
? ? ? ? int lenn = needle.size();
? ? ? ? for(int i=0;i<lenh;i++)
? ? ? ? {
? ? ? ? ? ? if(haystack[i] == needle[0])
? ? ? ? ? ? {
? ? ? ? ? ? ? bool res = checksame(haystack, needle, i);
? ? ? ? ? ? ? if(res==true)
? ? ? ? ? ? ? ? ? ? return i;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? return -1;
? ? }
};