From a72173b1ef5c3660b47b8364ca3e19ee5a7b7478 Mon Sep 17 00:00:00 2001 From: dekunma <53892579+dekunma@users.noreply.github.com> Date: Wed, 11 Nov 2020 14:23:51 +0800 Subject: [PATCH] =?UTF-8?q?=E3=80=90392.=20=E5=88=A4=E6=96=AD=E5=AD=90?= =?UTF-8?q?=E5=BA=8F=E5=88=97=E3=80=91=E3=80=90C++=E3=80=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...32\345\255\220\345\272\217\345\210\227.md" | 65 ++++++++++++++++++- 1 file changed, 64 insertions(+), 1 deletion(-) diff --git "a/\351\253\230\351\242\221\351\235\242\350\257\225\347\263\273\345\210\227/\344\272\214\345\210\206\346\237\245\346\211\276\345\210\244\345\256\232\345\255\220\345\272\217\345\210\227.md" "b/\351\253\230\351\242\221\351\235\242\350\257\225\347\263\273\345\210\227/\344\272\214\345\210\206\346\237\245\346\211\276\345\210\244\345\256\232\345\255\220\345\272\217\345\210\227.md" index c71e65f..e9c5b0f 100644 --- "a/\351\253\230\351\242\221\351\235\242\350\257\225\347\263\273\345\210\227/\344\272\214\345\210\206\346\237\245\346\211\276\345\210\244\345\256\232\345\255\220\345\272\217\345\210\227.md" +++ "b/\351\253\230\351\242\221\351\235\242\350\257\225\347\263\273\345\210\227/\344\272\214\345\210\206\346\237\245\346\211\276\345\210\244\345\256\232\345\255\220\345\272\217\345\210\227.md" @@ -168,4 +168,67 @@ boolean isSubsequence(String s, String t) {

-======其他语言代码====== \ No newline at end of file +======其他语言代码====== +[dekunma](https://www.linkedin.com/in/dekun-ma-036a9b198/) 提供C++代码 +**解法一:遍历(也可以用双指针):** +```C++ +class Solution { +public: + bool isSubsequence(string s, string t) { + // 遍历s + for(int i = 0; i < s.size(); i++) { + // 找到s[i]字符在t中的位置 + size_t pos = t.find(s[i]); + + // 如果s[i]字符不在t中,返回false + if(pos == std::string::npos) return false; + // 如果s[i]在t中,后面就只看pos以后的字串,防止重复查找 + else t = t.substr(pos + 1); + } + return true; + } +}; +``` + +**解法二:二分查找:** +```C++ +class Solution { +public: + bool isSubsequence(string s, string t) { + int m = s.size(), n = t.size(); + // 对 t 进行预处理 + vector index[256]; + for (int i = 0; i < n; i++) { + char c = t[i]; + index[c].push_back(i); + } + // 串 t 上的指针 + int j = 0; + // 借助 index 查找 s[i] + for (int i = 0; i < m; i++) { + char c = s[i]; + // 整个 t 压根儿没有字符 c + if (index[c].empty()) return false; + int pos = left_bound(index[c], j); + // 二分搜索区间中没有找到字符 c + if (pos == index[c].size()) return false; + // 向前移动指针 j + j = index[c][pos] + 1; + } + return true; + } + // 查找左侧边界的二分查找 + int left_bound(vector arr, int tar) { + int lo = 0, hi = arr.size(); + while (lo < hi) { + int mid = lo + (hi - lo) / 2; + if (tar > arr[mid]) { + lo = mid + 1; + } else { + hi = mid; + } + } + return lo; + } +}; +``` -- GitLab