• 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.

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

      这题难度不大。

      第一个程序(28ms):

     1 bool isIsomorphic(string s, string t) {
     2     unordered_map<char, char> hashMap;
     3     int sz = s.size();
     4     for(int i = 0; i < sz; i++)
     5     {
     6         if(hashMap.find(s[i]) != hashMap.end())
     7         {
     8             if(hashMap[s[i]] != t[i])
     9                 return false;
    10         }
    11         else
    12         {
    13             unordered_map<char, char>::iterator itr = hashMap.begin();
    14             for(; itr != hashMap.end(); itr++)
    15                 if(itr->second == t[i])
    16                     return false;
    17 
    18             hashMap[s[i]] = t[i];
    19         }
    20             
    21     }
    22     
    23     return true;
    24 }

      第二个程序(24ms):

     1 bool isIsomorphic(string s, string t) {
     2     unordered_map<char, char> hashMap;
     3     unordered_map<char, char> rHashMap;
     4     int sz = s.size();
     5     for(int i = 0; i < sz; i++)
     6     {
     7         if(hashMap.find(s[i]) != hashMap.end())
     8         {
     9             if(hashMap[s[i]] != t[i])
    10                 return false;
    11         }
    12         else
    13         {
    14             if(rHashMap.find(t[i]) != rHashMap.end())
    15                 return false;
    16             
    17             hashMap[s[i]] = t[i];
    18             rHashMap[t[i]] = s[i];
    19         }
    20     }
    21     
    22     return true;
    23 }

      看了网上别人的做法(少掉了哈希表查找的时间损耗),只需8ms

     1 bool isIsomorphic(string s, string t) {
     2     char map_s[128] = { 0 };
     3     char map_t[128] = { 0 };
     4     int len = s.size();
     5     for (int i = 0; i < len; ++i)
     6     {
     7         if (map_s[s[i]]!=map_t[t[i]]) return false;
     8         map_s[s[i]] = i+1;
     9         map_t[t[i]] = i+1;
    10     }
    11     
    12     return true;  
    13 }
  • 相关阅读:
    web报表工具FineReport使用中遇到的常见报错及解决办法(二)
    第四章 语言和声明
    第三章
    第五章 模式匹配
    Java生成Excel文件
    org.apache.jasper.JasperException: /pages/column.jsp (line: 8, column: 1) File "pathTags.jsp" not f
    web报表工具FineReport使用中遇到的常见报错及解决办法(一)
    web报表工具FineReport使用中遇到的常见报错及解决办法(一)
    人生中第一次面试——北漂18年(1)
    Perl 元字符
  • 原文地址:https://www.cnblogs.com/xiehongfeng100/p/4592333.html
Copyright © 2020-2023  润新知