zoukankan      html  css  js  c++  java
  • [LeetCode-JAVA] Isomorphic Strings

    题目:

    Given two strings s and t, determine if they are isomorphic.

    Two strings are isomorphic if the characters in s can be replaced to get t.

    All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.

    For example,
    Given "egg""add", return true.

    Given "foo""bar", return false.

    Given "paper""title", return true.

    Note:
    You may assume both s and t have the same length.

    思路:终于又出个简单的了,读完题就能看到,用map保存映射,同时还要判断value是否被映射过,用set进行过滤

    代码:

    public class Solution {
        public boolean isIsomorphic(String s, String t) {
            Map<Character, Character> map = new HashMap<Character, Character>();
            Set<Character> set = new HashSet<Character>();
            StringBuilder sb = new StringBuilder();
            for(int i = 0 ; i < len ; i++){
                if(!map.containsKey(s.charAt(i))){
                    if(!set.contains(t.charAt(i))){  //过滤 value t
                        map.put(s.charAt(i), t.charAt(i));  // s -> t
                        set.add(t.charAt(i));
                    }
                    else
                        return false;
                }
                sb.append(map.get(s.charAt(i)));    
            }
            return sb.toString().equals(t);
        }
    }
  • 相关阅读:
    Binary Search Tree Iterator 解答
    Invert Binary Tree 解答
    Min Stack 解答
    Trapping Raining Water 解答
    Candy 解答
    Jump Game II 解答
    Implement Hash Map Using Primitive Types
    Gas Station 解答
    Bucket Sort
    HashMap 专题
  • 原文地址:https://www.cnblogs.com/TinyBobo/p/4545702.html
Copyright © 2011-2022 走看看