From f5997e99876f01b08574e5f72fef8966d9556e7d Mon Sep 17 00:00:00 2001 From: Ryo Oshima Date: Sun, 11 Jan 2026 15:43:42 +0900 Subject: [PATCH] 392. Is Subsequence --- 392/solution1_1.java | 33 +++++++++++++++++++++++++++++++++ 392/solution2_1.java | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+) create mode 100644 392/solution1_1.java create mode 100644 392/solution2_1.java diff --git a/392/solution1_1.java b/392/solution1_1.java new file mode 100644 index 0000000..cf3c0e9 --- /dev/null +++ b/392/solution1_1.java @@ -0,0 +1,33 @@ +/* +・概要 +自力解法。5分ほどでAC + +・計算量 +時間:O(n) n:tの文字列の長さ。nは10^4なので、0.1msくらいで完了できそう +計算:O(1) + + +・解き方 +indexを使って、tを探索しながらsのindex番目の文字と一致するかをみていく。 +いわゆる2ポインタかな + + + +*/ +public class solution1_1 { + public boolean isSubsequence(String s, String t) { + if (s.length() == 0) { + return true; + } + int index = 0; + for (char c : t.toCharArray()) { + if (c == s.charAt(index)) { + index++; + if (s.length() == index) { + return true; + } + } + } + return false; + } +} diff --git a/392/solution2_1.java b/392/solution2_1.java new file mode 100644 index 0000000..c61daf9 --- /dev/null +++ b/392/solution2_1.java @@ -0,0 +1,39 @@ +/* +他の人の解法みた + +https://github.com/Satorien/LeetCode/pull/56/files +なるほど、indexを保持して、sのindex番目の文字がtにあるかを前回見つかったindexから右側で探すのか。2重ループかな? + +https://github.com/tokuhirat/LeetCode/pull/57/files +https://github.com/potrue/leetcode/pull/57/files +シンプル2ポインタ。whileって個人的に得意では無いので、どこかで練習しないとな +STEP2はかなり綺麗。STEP3は自分の解放とほぼ同じ + +https://github.com/ryosuketc/leetcode_arai60/pull/57/files +s, tのバリデーションを最初にいれている。確かに、仕様次第では安全にするためにこういうことをよくするのでいいなと思った。 +もし面接のときだったら、ここらへんは会話したい。 + +follow up +Follow up: Suppose there are lots of incoming s, say s1, s2, ..., sk where k >= 109, and you want to check one by one to see if t has its subsequence. In this scenario, how would you change your code? +についてはシンプルに考えると、sについてHashMapなどでメモ化しておくと、同じものを探索するときにすくかえせるから良さそう。もっと改善しようとすると、tについてHashMap>で各文字のindexを保持(複数もある)しておく。 +各sについて探索するときは、sの各文字について、先ほどのMapをもとにindexをupperboundでもとめていくことでlogtで求めることができる。よって全体でO(k*s*logt)で可能 +ということでwhileで実装してみる。 + +*/ + +public class solution2_1 { + public boolean isSubsequence(String s, String t) { + if (s.length() == 0) { + return true; + } + int sIndex = 0; + int tIndex = 0; + while (sIndex < s.length() && tIndex < t.length()) { + if (s.charAt(sIndex) == t.charAt(tIndex)) { + sIndex++; + } + tIndex++; + } + return sIndex == s.length(); + } +}