-
Notifications
You must be signed in to change notification settings - Fork 277
/
Copy pathIsSubsequence.java
104 lines (83 loc) · 2.12 KB
/
IsSubsequence.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
// @saorav21994
// TC : O(length of t)
// SC : O(1)
class Solution {
public boolean isSubsequence(String s, String t) {
int ls = s.length();
int lt = t.length();
int i = 0, j = 0;
while (i < ls) {
char chs = s.charAt(i);
boolean match = false;
while (j < lt && chs != t.charAt(j)) {
j += 1;
}
if (j >= lt && i < ls)
return false;
j += 1;
i += 1;
}
return true;
}
}
class Solution {
// TC : O(len(s + T))
// SC : O(1)
public boolean isSubsequence(String s, String t) {
if(s.length() == 0){
return true;
}
int i = 0;
int j = 0;
while(j<t.length() && i<s.length()){
if(s.charAt(i) == t.charAt(j)){
i++;
}
j++;
}
return i == s.length();
}
}
// Author : @romitdutta10
// TC : O(len(s + t))
// SC : O(1)
// Problem : https://leetcode.com/problems/is-subsequence/
class Solution {
public boolean isSubsequence(String s, String t) {
int n = s.length();
if(n > t.length()) {
return false;
}
if(s == null || s.length() == 0) {
return true;
}
int index = 0;
for(char c : t.toCharArray()) {
if(c == s.charAt(index)) {
index++;
if(index == n) {
return true;
}
}
}
return false;
}
}
// Author : @romitdutta10
// TC : O(len(s + t))
// SC : O(1)
// Problem : https://leetcode.com/problems/is-subsequence/
// Another interesting approach but space and time complexity remains same
class Solution {
public boolean isSubsequence(String s, String t) {
for (char ch : s.toCharArray()) {
int find = t.indexOf(ch);
if (find == -1) {
return false;
} else {
t = t.substring(find + 1);
}
}
return true;
}
}