这篇文章主要介绍了C++实现LeetCode(205.同构字符串),本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下
[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 s and t 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;
}
};
到此这篇关于C++实现LeetCode(205.同构字符串)的文章就介绍到这了,更多相关C++实现同构字符串内容请搜索编程学习网以前的文章希望大家以后多多支持编程学习网!
本文标题为:C++实现LeetCode(205.同构字符串)


基础教程推荐
- 如何C++使用模板特化功能 2023-03-05
- 一文带你了解C++中的字符替换方法 2023-07-20
- 详解c# Emit技术 2023-03-25
- C++使用easyX库实现三星环绕效果流程详解 2023-06-26
- C++中的atoi 函数简介 2023-01-05
- C语言 structural body结构体详解用法 2022-12-06
- C++详细实现完整图书管理功能 2023-04-04
- C利用语言实现数据结构之队列 2022-11-22
- C语言基础全局变量与局部变量教程详解 2022-12-31
- C/C++编程中const的使用详解 2023-03-26