zoukankan      html  css  js  c++  java
  • [LeetCode] 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.

    题目很简单,也很容易想到方法,就是记录遍历s的每一个字母,并且记录s[i]到t[i]的映射,当发现与已有的映射不同时,说明无法同构,直接return false。但是这样只能保证从s到t的映射,不能保证从t到s的映射,所以交换s与t的位置再重来一遍上述的遍历就OK了。

     1 class Solution {
     2 public:
     3     bool isIsomorphic(string s, string t) {
     4         if (s.length() != t.length()) return false;
     5         map<char, char> mp;
     6         for (int i = 0; i < s.length(); ++i) {
     7             if (mp.find(s[i]) == mp.end()) mp[s[i]] = t[i];
     8             else if (mp[s[i]] != t[i]) return false;
     9         }
    10         mp.clear();
    11         for (int i = 0; i < s.length(); ++i) {
    12             if (mp.find(t[i]) == mp.end()) mp[t[i]] = s[i];
    13             else if (mp[t[i]] != s[i]) return false;
    14         }
    15         return true;
    16     }
    17 };
  • 相关阅读:
    java纯数字加密解密实例
    C++手稿:std::string
    java裁剪图片
    java打开windows系统的浏览器
    Android手机无线adb
    office-word
    设计模式-享元模式(13)
    设计模式-外观模式(12)
    charles工具过滤腾讯视频播放器广告
    js将json格式的list转换为按某个字段分组的map数组
  • 原文地址:https://www.cnblogs.com/easonliu/p/4465650.html
Copyright © 2011-2022 走看看