word-pattern(mock)

注意:

// String要用equals,不然比较结果不对,会出bug
//
使用String.split

// boolean打印用 %b

 // abba 对应 cccc 也不行所以要用set记录

 

https://leetcode.com/problems/word-pattern/
https://leetcode.com/mockinterview/session/result/xsl1lbt/
package com.company;


import java.util.*;


class Solution {
    public boolean wordPattern(String pattern, String str) {
        // String要用equals,不然比较结果不对,会出bug
        // abba 对应 cccc 也不行, 所以要用set记录
        // 使用String.split

        String[] strs = str.split(" ");

        if (pattern.length() != strs.length) {
            System.out.println("here1");
            return false;
        }

        Map<String, String> mp = new HashMap<>();
        Set<String> st = new HashSet<>();

        for (int i=0; i<pattern.length(); i++) {
            String key = pattern.substring(i, i+1);
            if (mp.containsKey(key)) {
                // 开始用的 != 是错误的。要用equals
                if (!mp.get(key).equals(strs[i])) {
                    System.out.printf("k: %s, v: %s, str: %s
", key, mp.get(key), strs[i]);
                    return false;
                }
            }
            else {
                if (st.contains(strs[i])) {
                    return false;
                }
                else {
                    mp.put(key, strs[i]);
                    st.add(strs[i]);
                }
            }
        }
        return true;
    }
}

public class Main {

    public static void main(String[] args) {
        // write your code here
        System.out.println("Hello");

        String pattern = "abba";
        String str = "dog dog dog doa";

        Solution solution = new Solution();
        boolean ret = solution.wordPattern(pattern, str);
        System.out.printf("Get ret: %b
", ret);

    }
}
原文地址:https://www.cnblogs.com/charlesblc/p/5989263.html