zoukankan      html  css  js  c++  java
  • 【Leetcode】【Easy】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中相同位置的字符,所有出现的位置都相同。

    如果能记录每个字符出现的位置,同时遍历两个字符串,当遍历到新的字符时,检查各自字符之前出现的位置,之前的位置不一致,则返回false,否则继续检查下一对字符。

    对于记录位置和查找操作,最方便的是使用hash字典。字典中记录的是此字符上一次出现的位置。

    代码为:

     1 class Solution {
     2 public:
     3     bool isIsomorphic(string s, string t) {
     4         map<char, int> char_s;
     5         map<char, int> char_t;
     6         int len = s.size();
     7         
     8         for (int i = 0; i < len; ++i) {
     9             if (!char_s.count(s[i]))
    10                 char_s[s[i]] = i;
    11             if (!char_t.count(t[i]))
    12                 char_t[t[i]] = i;
    13             if (char_s[s[i]] != char_t[t[i]])
    14                 return false;
    15             char_s[s[i]] = i;
    16             char_t[t[i]] = i;
    17         }
    18         
    19         return true;
    20     }
    21 };
  • 相关阅读:
    2-Add Two Numbers
    1-Two Sum
    解决spark-shell输出日志过多的问题
    安装配置Hive
    src与bin版本的区别
    AES加密时抛出java.security.InvalidKeyException: Illegal key size or default parameters
    hosts文件修改问题
    Spark垃圾邮件分类(scala+java)
    Spark常用机器学习算法(scala+java)
    Spark自带Pi程序运行
  • 原文地址:https://www.cnblogs.com/huxiao-tee/p/4604694.html
Copyright © 2011-2022 走看看