leetcode 392. Is Subsequence

来源:互联网 发布:阿里云ecs使用教程 编辑:程序博客网 时间:2024/06/16 18:19

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 tt is potentially a very long (length ~= 500,000) string, and sis 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?

讲道理我不太想得通为什么这一题难度级别是Medium,这明明是一道简单题啊?

package leetcode;public class Is_Subsequence_392 {public boolean isSubsequence(String s, String t) {char[] sc=s.toCharArray();char[] tc=t.toCharArray();int scPointer=0;int tcPointer=0;while(scPointer<sc.length&&tcPointer<tc.length){if(sc[scPointer]==tc[tcPointer]){scPointer++;tcPointer++;}else{tcPointer++;}}if(scPointer==sc.length){return true;}else{return false;}}public static void main(String[] args) {// TODO Auto-generated method stubIs_Subsequence_392 i=new Is_Subsequence_392();System.out.println(i.isSubsequence("axc", "ahbgdc"));}}
大神想法跟我一样。

另外有大神用了下面的方法:Collections.binarySearch的返回值是搜索键的索引,与indexOf方法差不多。

public boolean isSubsequence(String s, String t) {        List<Integer>[] idx = new List[256]; // Just for clarity        for (int i = 0; i < t.length(); i++) {            if (idx[t.charAt(i)] == null)                idx[t.charAt(i)] = new ArrayList<>();            idx[t.charAt(i)].add(i);        }                int prev = 0;        for (int i = 0; i < s.length(); i++) {            if (idx[s.charAt(i)] == null) return false; // Note: char of S does NOT exist in T causing NPE            int j = Collections.binarySearch(idx[s.charAt(i)], prev);            if (j < 0) j = -j - 1;//其实我不太懂这一步在干嘛,为啥会出现j<0            if (j == idx[s.charAt(i)].size()) return false;            prev = idx[s.charAt(i)].get(j) + 1;        }        return true;}
下面有对这个方法进行的详细说明:

The prev variable is an index where previous character was picked from the sequence. And for the next character to be picked, you have to select it only after this index is the string 'T'.

For instance, if S = "abcd" and T = "abdced".
The index list mapping looks like,

a -> 0b -> 1c -> 3d -> 2,5e -> 4

After you pick a, and b, c will be picked, and index is 3. Now if you have to pick d, you can't pick index 2 because c was picked at 3, so you have to binary search for index which comes after 3. So it returns 5.


原创粉丝点击