java 使用指针可以解答的算法 学习记录

 

a 字符串被包含在 b 字符串中

示例 1:

输入:s = "abc", t = "ahbgdc"
输出:true
示例 2:

输入:s = "axc", t = "ahbgdc"
输出:false
@Test
public  void test() {
    String s = "abc", t = "ahbgdc";

    int sPoint = 0,tPoint = 0;
    while (sPoint < s.length() && tPoint<t.length()) {
        if (s.charAt(sPoint) == t.charAt(tPoint)){
            sPoint++;
        }
        tPoint++;
    }
    System.out.println(sPoint== s.length());
}

判断s 是t 的连续子串

@Test
public void test() {
    String s = "abc", t = "ahabcgdc";

    int sPoint = 0, tPoint = 0;
    while (tPoint < t.length()) {
        if (s.charAt(sPoint) == t.charAt(tPoint)) {
            sPoint++;
            if (sPoint == s.length()) {
                break;
            }
        } else {
            sPoint = 0;
        }
        tPoint++;
    }
    System.out.println(sPoint == s.length());
}

字符串左移右移

@Test
public void moveLeft(){
    String xx = "abcd123";
    int k = 3;
    char[] cs = new char[256];
    int index = 0;
    for (int i = 0; i < xx.length(); i++) {
        cs[index++] = xx.charAt((i+xx.length()+k)%xx.length());
    }
    for (int i = 0; i < index; i++) {
        System.out.println(cs[i]);
    }
}

@Test
public void moveRight(){
    String xx = "abcd123";
    int k = 3;

    char[] cs = new char[256];
    int index = 0;
    for (int i = 0; i < xx.length(); i++) {
        cs[index++] = xx.charAt((i+xx.length()-k)%xx.length());
    }
    for (int i = 0; i < index; i++) {
        System.out.println(cs[i]);
    }
}

判断两次字符串的字符完全相同

@Test
public void test(){
    String s = "anagram", t = "nagaram";
    String s1 = "rat", t1 = "car";
    System.out.println(isSame(s,t));
    System.out.println(isSame(s1,t1));
}

public boolean isSame(String s,String t) {
    if (s.length() != t.length()) {
        return false;
    }
    int[] check = new int[26];
    for (int i = 0; i < t.length(); i++) {
        check[s.charAt(i)-'a'] ++;
        check[t.charAt(i)-'a'] --;
    }

    for (int i : check) {
        if (i != 0) {
            return false;
        }
    }
    return true;
}

计算一组字符集合可以组成的回文字符串的最大长度

计算一组字符集合可以组成的回文字符串的最大长度


@Test
public void test(){
    String xx = "abccaa";
    System.out.println(LongestPalindrome(xx));

}
public int LongestPalindrome(String x) {
    char[] charArray = x.toCharArray();
    int[] xc = new int[26];
    for (char c : charArray) {
        xc[c-'a'] ++;
    }
    int res = 0;
    for (int i = 0; i < xc.length; i++) {
        res += (xc[i] /2) *2;
    }
    return  res == charArray.length?res:res+1;
}

第一个不重复的字符



@Test
public void call() {
    String xx = "google";
    System.out.println(test(xx));
}
public int test(String xx){
    int[] xs = new int[26];
    for (int i = 0; i < xx.length(); i++) {
        xs[xx.charAt(i)-'a'] ++;
    }

    for (int i = 0; i < xx.length(); i++) {
        if (xs[xx.charAt(i)-'a']  == 1) {
            return i;
        }
    }
    return -1;
}