码迷,mamicode.com
首页 > 其他好文 > 详细

392. Is Subsequence

时间:2017-07-01 12:43:29      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:arraylist   for   pre   binary   search   com   class   sub   htm   

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

标签:arraylist   for   pre   binary   search   com   class   sub   htm   

原文地址:http://www.cnblogs.com/apanda009/p/7101774.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!