• [lintcode]638.Strings Homomorphism


    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.

    注意事项:

    You may assume both s and t have the same length.

    样例:

    Given s = "egg", t = "add", return true.

    Given s = "foo", t = "bar", return false.

    Given s = "paper", t = "title", return true.

    解题思路:

    一开始我一直钻到牛角尖里面,一直想着字母一一对应的替换。

    最近在看算法,这道题应该算是一道很简单的哈希表。

    其实就是要记录每一个字母出现的次数和它对应的位置。

    以egg和add为例:

    'g'和'd'出现了两次,就是[1,2,2],[1,2,2]

    'foo':[1,2,2];bar:[1,1,1]

    然后我又再一次陷入了这个存数组的漩涡里面。。。我试图搞一个数组,按照index把出现次数存进去。。。

    后来在网上搜索了一下,其实只要按照string的顺序(位置对应),读出每一个char的出现次数(次数对应)就可以以了。

     1 class Solution {
     2 public:
     3     /*
     4      * @param s: a string
     5      * @param t: a string
     6      * @return: true if the characters in s can be replaced to get t or false
     7      */
     8     bool isIsomorphic(string s, string t) {
     9         // write your code here
    10        map <char, int> word1,word2; //<key:char类型,value:int类型>
    11        for(int i = 0; i<s.size(); i++){
    12            word1[s[i]]++;
    13            word2[t[i]]++;
    14        }
    15        for(int i = 0; i< s.size(); i++){
    16            if(word1[s[i]]!=word2[t[i]]){
    17                return false;
    18            }
    19        }
    20        return true;
    21     }
    22 };
  • 相关阅读:
    AutoCompleteTextView控件的使用
    menu菜单
    fragment之间的通信
    fragment的生命周期
    用模型取代字典的好处
    使用fragment兼容低版本的写法
    模拟微信主界面
    动态替换fragment
    fragment入门
    Spring MVC学习总结(1)——Spring MVC单元测试
  • 原文地址:https://www.cnblogs.com/hopping/p/7724342.html
Copyright © 2020-2023  润新知