• No.205 Ismorphic Strings


    No.205 Ismorphic 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,则s和t是同构的
      注:两个字符不能映射到同一字符,但字符可映射到它本身

     1 #include "stdafx.h"
     2 #include <map>
     3 #include <vector>
     4 #include <iostream>
     5 using namespace std;
     6 
     7 class Solution
     8 {
     9 public:
    10     bool isIsomorphic(string s, string t)
    11     {//字符串同构判断
    12      //已知s和t大小相同,s中的字符经过相同的映射可转换为t,则s和t是同构的
    13      //注:两个字符不能映射到同一字符,但字符可映射到它本身
    14      int size = s.size();
    15      if(size <= 1)
    16          return true;//大小为1,肯定同构
    17      map<char,char> mapping;
    18      for(int i=0; i<size; i++)
    19      {
    20          if(mapping.find(s[i]) == mapping.end())//尚未建立映射
    21          {
    22              for(auto const &it : mapping)
    23                 if(it.second == t[i])//两个字符映射到同一字符了!!
    24                     return false;
    25              mapping[s[i]] = t[i];
    26          }
    27          else
    28              if(t[i] != mapping[s[i]])
    29                  return false;
    30          
    31      }
    32      return true;
    33     }
    34 };
    35 
    36 int main()
    37 {
    38     Solution sol;
    39     cout << boolalpha;
    40 
    41     cout << sol.isIsomorphic("egg","add")<<endl;//true
    42     cout << sol.isIsomorphic("foo","bar")<<endl;//false
    43     cout << sol.isIsomorphic("paper","title")<<endl;//true
    44     cout << sol.isIsomorphic("abcda","bcceb")<<endl;//两个字符映射相同
    45 }

     

  • 相关阅读:
    数据结构化与保存
    使用正则表达式,取得点击次数,函数抽离
    爬取校园新闻首页的新闻
    网络爬虫基础练习
    综合练习:词频统计
    Hadoop综合大作业
    理解MapReduce
    熟悉常用的Hbase操作
    熟悉的HDFS操作
    爬取晨星网对各公司主要职位的分析
  • 原文地址:https://www.cnblogs.com/dreamrun/p/4566339.html
Copyright © 2020-2023  润新知