392. Is Subsequence
阿新 • • 發佈:2017-07-01
ray public add note urn binary null tco string
https://leetcode.com/problems/is-subsequence/#/solutions
http://www.cnblogs.com/EdwardLiu/p/6116896.html
public boolean isSubsequence(String s, String t) { int j = 0, i = 0; while (j < t.length() && i < s.length()) { if (s.charAt(i) == t.charAt(j)) { i++; j++; } else { j++; } } if (i == s.length()) { return true; } else { return false; } }
Follow Up:
The best solution is to create a map for String t, key is char, value is the index of appearance in ascending order
public boolean isSubsequence(String s, String t) { List<Integer>[] idx = new List[256]; // Just for clarity 字典集合, 每一個字母的ASCII 碼當作鍵, 在t中的順序當作值 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; // 前一個字母在t中的坐標, 控制升序 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; //在升序後找不到false prev = idx[s.charAt(i)].get(j) + 1; //在t中查找當前s的字母比s中的前一個字母在t中升序的坐標
}
return true;
}
392. Is Subsequence