数据结构之字符串

最长回文串 题目 解析

ASCⅡ表有256个位。

class Solution {
    public int longestPalindrome(String s) {
        int[] cnts = new int[256];
        for (char c : s.toCharArray()) {
            cnts[c]++;
        }
        int count = 0;
        for (int x : cnts) {
            count += x/2*2;
        }
        return count == s.length() ? count : count+1;
    }
}

 

字符串同构 题目 解析

又来复习一波哈希表

class Solution {
    public boolean isIsomorphic(String s, String t) {
        Map<Character, Character> hashmap = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            if (!hashmap.containsKey(s.charAt(i))) {
                if (hashmap.containsValue(t.charAt(i))) {
                    return false;
                }
                else {
                    hashmap.put(s.charAt(i), t.charAt(i));
                }
            }
            else if (hashmap.get(s.charAt(i)) != t.charAt(i)) {
                return false;
            }
        }
        return true;
    }
}

记录上一次出现的位置,如果相等,那么就是重构。

class Solution {
    public boolean isIsomorphic(String s, String t) {
        int[] a = new int[256];
        int[] b = new int[256];
        for (int i = 0; i < s.length(); i++) {
            char sc = s.charAt(i);
            char tc = t.charAt(i);
            if (a[sc] != b[tc]) {
                return false;
            } 
            a[sc] = i+1;
            b[tc] = i+1;
        }
        return true;
    }
}

 

翻转字符串里的单词 题目 解析

 

重复的子字符串 题目 解析

KMP的next数组,看我的KMP笔记

class Solution {
    public boolean repeatedSubstringPattern(String s) {
        int n = s.length();
        int[] next = new int[n];
        int j = -1;
        next[0] = j;
        for (int i = 1; i < n; i++) {
            while (j >= 0 && s.charAt(j+1) != s.charAt(i)) {
                j = next[j];
            }
            if (s.charAt(j+1) == s.charAt(i)) {
                j++;
            }
            next[i] = j;
        }
        if (next[n-1] != -1 && n % (n-(next[n-1]+1)) == 0) {
            return true;
        }
        return false;
    }
}

 

posted @ 2020-11-12 20:41  CPJ31415  阅读(107)  评论(0)    收藏  举报