LeetCode 392. Is Subsequence

Given a string s and a string t, check if s is subsequence of t.

You may assume that there is only lower case English letters in both s and t. t is potentially a very long (length ~= 500,000) string, and s is a short string (<=100).

A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ace" is a subsequence of "abcde" while "aec" is not).

Example 1:
s = "abc", t = "ahbgdc"

Return true.

Example 2:
s = "axc", t = "ahbgdc"

Return false.

Follow up:
If there are lots of incoming S, say S1, S2, ... , Sk where k >= 1B, 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是t的子序列,t可以这样构成:在s字符串中的任意位置插入任意长度的字符串。

【思路】

1.维持两个字符串指针,分别指向s和t,如果当前字符相同,则指针都向后移动,否则只移动t的指针,直到s中出现的字符都在t中出现过了,我们可以判定s是t的子序列。代码如下:

 1 public class Solution {
 2     public boolean isSubsequence(String s, String t) {
 3         int sindex = 0, tindex = 0;
 4         while(sindex < s.length() && tindex < t.length()) {
 5             if(s.charAt(sindex) == t.charAt(tindex)) {
 6                 sindex++;
 7             }
 8             tindex++;
 9         }
10         if(sindex == s.length()) return true;
11         return false;
12     }
13 }

 

 

2.我们对上面的代码进行改进,代码如下:

 1 public class Solution {
 2     public boolean isSubsequence(String s, String t) {
 3         if(t.length() < s.length()) return false;
 4         int prev = 0;
 5         for(int i = 0; i < s.length();i++) {
 6             char tempChar = s.charAt(i);
 7             prev = t.indexOf(tempChar,prev);
 8             if(prev == -1) return false;
 9             prev++;
10         }
11         
12         return true;
13     }
14 }

 

可以看到这两种方法的差别很大。之所以有这样的差别,是因为在第一种方法中我们每查看一个字符就要调用一次charAt()方法。而在第二种方法中使用indexOf()方法可以直接跳过不匹配的字符,这样大大减少的了函数的调用次数,减少时间复杂度,简直太棒了!

posted @ 2016-11-30 14:13  Black_Knight  阅读(573)  评论(0编辑  收藏  举报