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);
        }
    }
  • 相关阅读:
    二维数组排序
    php-快速排序
    sql优化相关
    全页面静态化缓存
    php--1-100相加之和
    php--阶乘
    socket
    posix_getpid 函数win下失效问题
    水仙花数
    常用的魔术方法
  • 原文地址:https://www.cnblogs.com/TinyBobo/p/4545702.html
Copyright © 2011-2022 走看看