LeetCode205.同构字符串 LeetCode290.单词规律

LeetCode205.同构字符串 LeetCode290.单词规律_第1张图片
使用数组来记录上一次出现的索引值

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

LeetCode205.同构字符串 LeetCode290.单词规律_第2张图片
使用HashMap来记录字符和字符串的对应关系

class Solution {
    public boolean wordPattern(String pattern, String str) {
        String[] arr = str.split(" ");
        if(pattern.length() != arr.length){
            return false;
        }
        Map<Character,String> map = new HashMap<>();
        for(int i = 0;i < arr.length;i++){
            char c = pattern.charAt(i);
            if(map.containsKey(c)){
                if(!map.get(c).equals(arr[i])){
                    return false;
                }
            }else{
                if(map.containsValue(arr[i])){
                    return false;
                }
                map.put(c,arr[i]);
            }
        }
        return true;
    }
}

你可能感兴趣的:(算法与数据结构,字符串,leetcode)