isSubsequence() + indexOf() 板子 --- Java版

isSubsequence()

public class Solution {
    // t = "abcde"
    // s = "acd"
    private boolean isSubsequence(String s, String t) {
        if (t.length() < s.length()) {
            return false;
        }
        if (s.length() == 0) {
            return t.length() == 0;
        }
        
        // i 表示 s的下标,j表示t的下标
        for (int i = 0, j = 0; i < s.length(); i++, j++) {
            char sCh = s.charAt(i);
            j = t.indexOf(sCh, j);
            if (j < 0) {
                return false;
            }
        }
        
        return true;
    }
    
}

indexOf()

public class Solution {
    // 输入:t = "hello", s = "ll"
    // 输出:2
    public int indexOf(String t, String s) {
        if (t.length() < s.length()) {
            return -1;
        }
        
        if (s.length() == 0) {
            return 0;
        }
        
        // i 表示 t的下标,j表示s的下标
        for (int i = 0; i < t.length() - s.length() + 1; i++) {
            if (t.charAt(i) == s.charAt(0)) {
                int j = 0;
                while (i + j < t.length() && j < s.length() && t.charAt(i + j) == s.charAt(j)) {
                    j++;
                }
                
                if (j == s.length()) {
                    return i;
                }
            }
        }
        
        return -1;
    }
}

你可能感兴趣的:(isSubsequence() + indexOf() 板子 --- Java版)