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);
        }
    }
  • 相关阅读:
    枚举子集 Codeforces306 Div2 B
    UVA140 剪枝
    回溯法浅谈
    UVA10976
    UVA11059
    BZOJ3355
    hdu 2509 博弈 *
    博弈专题
    hdu 1404 找sg ***
    hdu 4759 大数+找规律 ***
  • 原文地址:https://www.cnblogs.com/TinyBobo/p/4545702.html
Copyright © 2011-2022 走看看