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;
        }
    };
  • 相关阅读:
    Struts2框架的学习遇到的问题1
    博客开通第100天
    RTK(Real Time Kinematic)实时动态差分定位技术
    HSRP 协议/ VRRP 协议(热备份路由协议)
    PKI 公钥基础设施
    路由器的工作原理
    VLAN基础知识
    Linux系统的 粘滞位、sgid和suid
    Kali Linux三步安装中文输入法(极简)
    ACL 包过滤技术
  • 原文地址:https://www.cnblogs.com/jdneo/p/4749986.html
Copyright © 2011-2022 走看看