您的位置:首页 > 房产 > 建筑 > 幼儿园主题网络设计图教案_名字logo设计在线生成免费_如何创建网页链接_怎么制作网站教程手机

幼儿园主题网络设计图教案_名字logo设计在线生成免费_如何创建网页链接_怎么制作网站教程手机

2024/12/27 5:20:20 来源:https://blog.csdn.net/sinat_41679123/article/details/144236872  浏览:    关键词:幼儿园主题网络设计图教案_名字logo设计在线生成免费_如何创建网页链接_怎么制作网站教程手机
幼儿园主题网络设计图教案_名字logo设计在线生成免费_如何创建网页链接_怎么制作网站教程手机

Description

You are given two 0-indexed strings str1 and str2.

In an operation, you select a set of indices in str1, and for each index i in the set, increment str1[i] to the next character cyclically. That is ‘a’ becomes ‘b’, ‘b’ becomes ‘c’, and so on, and ‘z’ becomes ‘a’.

Return true if it is possible to make str2 a subsequence of str1 by performing the operation at most once, and false otherwise.

Note: A subsequence of a string is a new string that is formed from the original string by deleting some (possibly none) of the characters without disturbing the relative positions of the remaining characters.

Example 1:

Input: str1 = "abc", str2 = "ad"
Output: true
Explanation: Select index 2 in str1.
Increment str1[2] to become 'd'. 
Hence, str1 becomes "abd" and str2 is now a subsequence. Therefore, true is returned.

Example 2:

Input: str1 = "zc", str2 = "ad"
Output: true
Explanation: Select indices 0 and 1 in str1. 
Increment str1[0] to become 'a'. 
Increment str1[1] to become 'd'. 
Hence, str1 becomes "ad" and str2 is now a subsequence. Therefore, true is returned.

Example 3:

Input: str1 = "ab", str2 = "d"
Output: false
Explanation: In this example, it can be shown that it is impossible to make str2 a subsequence of str1 using the operation at most once. 
Therefore, false is returned.

Constraints:

1 <= str1.length <= 10^5
1 <= str2.length <= 10^5
str1 and str2 consist of only lowercase English letters.

Solution

Solved after hints…

It’s like how we decide if str2 is a subsequence of str1, only this time we could change str1. To decide the subsequence, we could use 2 pointers on each string. If the str1[i] is the same as str2[j], move both i, j forward. Otherwise if str1[i] can increment cyclically and they match, we also move i, j both forward. Otherwise we only move i forward.

After comparing, if j reaches at the end of str2, then it’s a subsequence of str1.

Time complexity: o ( m + n ) o(m+n) o(m+n)
Space complexity: o ( 1 ) o(1) o(1)

Code

class Solution:def canMakeSubsequence(self, str1: str, str2: str) -> bool:p1, p2 = 0, 0while p1 < len(str1) and p2 < len(str2):if str1[p1] == str2[p2]:p1 += 1p2 += 1elif chr((ord(str1[p1]) + 1 - ord('a')) % 26 + ord('a')) == str2[p2]:p1 += 1p2 += 1else:p1 += 1return p2 == len(str2)

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com