zoukankan      html  css  js  c++  java
  • 【LeetCode】205. 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.

    提示:

    此题的关键是要保证s与t中每一个字符之间都是一一对应的关系(即不能出现一对多或多对一的情况)。我们可以维护两张哈希表,一张保存s到t的映射关系,另一张保存t到s的映射关系。如果用C++的unordered_map是可以实现的,但是对于这个问题,由于可以确定输入的字符串中所有可能出现的字符不会超过128种,因此用数组代替unordered_map可以获得性能上的提升。

    代码:

    class Solution {
    public:
        bool isIsomorphic(string s, string t) {
            if (s.length() == 0) return true;
            char dic_s[128] = {0}, dic_t[128] = {0};
            for (int i = 0; i < s.length(); ++i) {
                if (dic_s[s[i]] == 0 && dic_t[t[i]] == 0) {
                    dic_s[s[i]] = t[i];
                    dic_t[t[i]] = s[i];
                } else {
                    if (dic_s[s[i]] != t[i] || dic_t[t[i]] != s[i]) {
                        return false;
                    }
                }
            }
            return true;
        }
    };
  • 相关阅读:
    获取元素位置信息和所占空间大小(via:js&jquery)
    原生js获取元素的样式信息
    真的了解js生成随机数吗
    js中有关滑动问题的一些理解
    禁止遮罩层以下屏幕滑动----正解(更新版)
    js中的null和undefined
    通过ajax获得json数据后格式的转换
    悬浮导航栏的实现以及导航跳转
    css selector
    视频播放器
  • 原文地址:https://www.cnblogs.com/jdneo/p/4749986.html
Copyright © 2011-2022 走看看