1. 程式人生 > 實用技巧 >android 功耗(1)---android 功耗分析方法和優化

android 功耗(1)---android 功耗分析方法和優化

根據《演算法導論》上的虛擬碼修改,書上的字串索引從1開始,需要修改為從0開始

 1 class Solution {
 2 public:
 3     int strStr(string haystack, string needle) {
 4         int sz1 = haystack.size(), sz2 = needle.size();
 5         if (sz2 == 0) {
 6             return 0;
 7         }
 8         if (sz1 == 0) {
 9             return -1;
10         }
11 int q = -1; 12 vector<int>trans = _helper(needle); 13 for (int i = 0; i < sz1; ++i) { 14 while (q > -1 && haystack[i] != needle[q+1]) { 15 q = trans[q]; 16 } 17 if (haystack[i] == needle[q+1]) { 18 ++q;
19 } 20 if (q == sz2-1) { 21 return i - sz2+1; 22 } 23 } 24 return -1; 25 } 26 private: 27 vector<int> _helper(string needle) { 28 int sz = needle.size(); 29 vector<int>res(sz, 0); 30 int k = -1
; 31 res[0] = -1; 32 //q表示狀態 33 for (int q = 1; q < sz; ++q) { 34 while (k > -1 && needle[k+1] != needle[q]) { 35 k = res[k]; 36 } 37 if (needle[q] == needle[k+1]) { 38 ++k; 39 } 40 res[q] = k; 41 } 42 return res; 43 } 44 };