C++实现LeetCode(205.同构字符串)

作者:Grandyang 时间:2023-06-21 04:06:54 

[LeetCode] 205. 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.

Example 1:

Input: s = "egg", t = "add"
Output: true

Example 2:

Input: s = "foo", t = "bar" Output: false

Example 3:

Input: s = "paper", t = "title"
Output: true

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

这道题让我们求同构字符串,就是说原字符串中的每个字符可由另外一个字符替代,可以被其本身替代,相同的字符一定要被同一个字符替代,且一个字符不能被多个字符替代,即不能出现一对多的映射。根据一对一映射的特点,需要用两个 HashMap 分别来记录原字符串和目标字符串中字符出现情况,由于 ASCII 码只有 256 个字符,所以可以用一个 256 大小的数组来代替 HashMap,并初始化为0,遍历原字符串,分别从源字符串和目标字符串取出一个字符,然后分别在两个数组中查找其值,若不相等,则返回 false,若相等,将其值更新为 i + 1,因为默认的值是0,所以更新值为 i + 1,这样当 i=0 时,则映射为1,如果不加1的话,那么就无法区分是否更新了,代码如下:


class Solution {
public:
   bool isIsomorphic(string s, string t) {
       int m1[256] = {0}, m2[256] = {0}, n = s.size();
       for (int i = 0; i < n; ++i) {
           if (m1[s[i]] != m2[t[i]]) return false;
           m1[s[i]] = i + 1;
           m2[t[i]] = i + 1;
       }
       return true;
   }
};

来源:https://www.cnblogs.com/grandyang/p/4465779.html

标签:C++,同构字符串,LeetCode
0
投稿

猜你喜欢

  • 详解Android Flutter中SliverAppBar的使用教程

    2023-06-23 12:11:27
  • flutter ExpansionTile 层级菜单的实现

    2023-06-15 16:04:01
  • 基于Flutter实现多边形和多角星组件

    2023-06-19 06:02:50
  • Flutter 使用fluro的转场动画进行页面切换

    2023-06-17 11:49:26
  • Flutter开发中的路由参数处理

    2023-06-21 04:27:48
  • Flutter Widget开发之Focus组件图文详解

    2023-06-21 03:47:41
  • flutter material widget组件之信息展示组件使用详解

    2023-06-22 08:45:35
  • Flutter应用集成极光推送的实现示例

    2023-06-24 03:51:04
  • Flutter 剪裁组件的使用

    2023-06-18 13:15:04
  • Flutter实现抽屉动画

    2023-06-18 01:49:19
  • Swift洗牌动画效果的实现方法

    2023-06-21 14:01:56
  • C++实现LeetCode(9.验证回文数字)

    2023-06-21 00:20:38
  • Flutter实现矩形取色器的封装

    2023-06-19 04:08:47
  • Android开发组件flutter的20个常用技巧示例总结

    2023-06-19 17:25:23
  • iOS应用中使用Toolbar工具栏方式切换视图的方法详解

    2023-06-21 09:24:48
  • 使用flutter创建可移动的stack小部件功能

    2023-06-21 12:28:25
  • Flutter 如何正确显示SnackBar

    2023-06-23 13:00:40
  • flutter TextField换行自适应的实现

    2023-06-21 01:21:39
  • Flutter路由传递参数及解析实现

    2023-06-22 11:48:45
  • Flutter 通过Clipper实现各种自定义形状的示例代码

    2023-06-19 14:25:11
  • asp之家 软件编程 m.aspxhome.com