Skip to content

Commit 4f793f1

Browse files
committed
Add solution of IsSubsequence task
1 parent ecd903c commit 4f793f1

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package by.andd3dfx.string;
2+
3+
/**
4+
* <pre>
5+
* <a href="https://leetcode.com/problems/is-subsequence/description/">Task description</a>
6+
*
7+
* Given two strings s and t, return true if s is a subsequence of t, or false otherwise.
8+
* A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters
9+
* without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not).
10+
*
11+
* Example 1:
12+
* Input: s = "abc", t = "ahbgdc"
13+
* Output: true
14+
*
15+
* Example 2:
16+
* Input: s = "axc", t = "ahbgdc"
17+
* Output: false
18+
* </pre>
19+
*/
20+
public class IsSubsequence {
21+
22+
public static boolean isSubsequence(String s, String t) {
23+
var last = -1;
24+
for (var ch : s.toCharArray()) {
25+
var index = t.indexOf(ch, last + 1);
26+
if (index == -1) {
27+
return false;
28+
}
29+
last = index;
30+
}
31+
return true;
32+
}
33+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package by.andd3dfx.string;
2+
3+
import static org.assertj.core.api.Assertions.assertThat;
4+
5+
import org.junit.Test;
6+
7+
public class IsSubsequenceTest {
8+
9+
@Test
10+
public void isSubsequence() {
11+
assertThat(IsSubsequence.isSubsequence("abc", "ahbgdc")).isTrue();
12+
assertThat(IsSubsequence.isSubsequence("axc", "ahbgdc")).isFalse();
13+
14+
assertThat(IsSubsequence.isSubsequence("abc", "aaccbb")).isFalse();
15+
assertThat(IsSubsequence.isSubsequence("andrei", "rtaanghtdretyia")).isTrue();
16+
}
17+
}

0 commit comments

Comments
 (0)