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的一個子序列。子序列是指s中的字母均按照相對位置存在於t中,好比"abc"是"ahbfdc"的一個子序列,可是"axc"就不是"ahbgdc"的一個子序列。java
java中提供了一個String.indexOf(char c, int startIndex)
的方法,這個方法是指從字符串中的startIndex位置開始日後找,返回第一個c所在的下標,若是找不到,則返回-1。利用這個方法咱們能夠快速的解決這個問題。面試
public boolean isSubsequence(String s, String t) { if(s==null || s.length()==0) return true; int start = -1; for(int i = 0 ; i<s.length() ; i++) { char c = s.charAt(i); //從上一個字符的起始位置開始,找下一個字符第一次出現的下標。若是不存在該字符,則說明不是子序列 start = t.indexOf(c, start+1); if(start < 0) return false; } return true; }
二分法的思路主要是指,首先咱們遍歷字符串t,找到每一個字符在t中出現的位置。當咱們知道每一個字符在t中出現的全部下標後,就開始遍歷s,並開始找到距離上一個字符所在的位置以後的當前字符的最小下標。
舉例:微信
s="abc" t="acbgbc" 遍歷t以後能夠獲得這樣一個字段: a:{0} b:{2,4} g:{3} c:{1,5} 以後遍歷s,並用一個index來記錄當前字符所在的下標,index初始時爲-1。 s[0] = a, a:{0} -> index = 0 s[1] = b, b:{2,4} -> index = 2 s[2] = c, c:{1,5} -> index=5
能夠看到咱們可以找到一個合法的序列,使得當前字母的起始下標始終大於上一個字母的下標。this
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; if (j == idx[s.charAt(i)].size()) return false; prev = idx[s.charAt(i)].get(j) + 1; } return true; }
想要了解更多開發技術,面試教程以及互聯網公司內推,歡迎關注個人微信公衆號!將會不按期的發放福利哦~spa