87. Scramble String

小米MIUI 12免REC解锁Root:Magisk Manager与Fastboot实战指南 本文详细介绍了小米MIUI 12免REC解锁Root的完整流程,涵盖Magisk Manager与Fastboot的实战操作。从解锁前的准备工作到提取boot.img、Magisk修补技巧,再到Fastboot刷入全流程,提供了常见问题解决方案和进阶优化建议,帮助用户安全高效地获取Root权限。 阅读详情

Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively.

Below is one possible representation of s1 = "great":

    great
   /    \
  gr    eat
 / \    /  \
g   r  e   at
           / \
          a   t

To scramble the string, we may choose any non-leaf node and swap its two children.

For example, if we choose the node "gr" and swap its two children, it produces a scrambled string "rgeat".

    rgeat
   /    \
  rg    eat
 / \    /  \
r   g  e   at
           / \
          a   t

We say that "rgeat" is a scrambled string of "great".

Similarly, if we continue to swap the children of nodes "eat" and "at", it produces a scrambled string "rgtae".

    rgtae
   /    \
  rg    tae
 / \    /  \
r   g  ta  e
       / \
      t   a

We say that "rgtae" is a scrambled string of "great".

Given two strings s1 and s2 of the same length, determine if s2 is a scrambled string of s1.

这个问题可以用DP方法解决,思路如下:

先分析情况:

1.字符串长度为1, 若s1 == s2 , true

2.字符串长度为2, 如s1=“xy", 那么s2="xy“或”xy"为true

3.字符串长度为n,s1=XY, 那么s2=XY / YX返回true

采用一个三维数组,例如vec[1][i][j] 代表长度为1,s1下标为 i ,s2下标为 j 时是否符合scamble 


class Solution {
public:
    bool isScramble(string s1, string s2) {
        size_t len_s1 = s1.length();
        size_t len_s2 = s2.length();
        
        if(len_s1 != len_s2)
            return false;
        
        vector<vector<vector<bool>>> vec(len_s1+1, vector<vector<bool>>(
                                        len_s1, vector<bool>(len_s1, false)));
        for(int i=0; i<len_s1; ++i)
            for(int j=0; j<len_s1; ++j)
                vec[1][i][j] = s1[i] == s2[j];
        
        for(int n=2; n<=len_s1; ++n){    //从2开始,因为长度为1之前已经计算过。
            for(int i=0; i<=len_s1-n; ++i){
                for(int j=0; j<=len_s1-n; ++j){
                    for(int k=1; k<n; ++k){
                         if(vec[k][i][j] && vec[n-k][i+k][j+k]
                            || vec[k][i][j+n-k] && vec[n-k][i+k][j]){
                            vec[n][i][j] = true;
                            break;
                        }
                    }
                }
            }
        }
        return vec[len_s1][0][0];
    }
};


n代表当前字符串长度,n从1开始一直到最大值len_s1,自底向上。

我们发现,对于i和j进行双重循环遍历,将会自底向上求得当前长度为n时的字符串是否为Scramble,如果是,那么回break循环,break只能跳出一重循环。当我们的n为len_s1时,此时 i 和 j 只可能为0,这时当前字符串长度为len_s1,它的一部分vec[1][i][j] 和vec[len_s1-1][i][j] (即vec[n-1][i][j]))在之前由底向上已经计算过,所以vec[len_s1][0][0] = true,返回。

更多算法:

#include <iostream>
#include <vector>
#include <string>
#include <assert.h>
#include <map>
#include <unordered_map>

class solution1 {
#ifdef _USE_METHOD_1_
//methon 1
public:
	bool is_scramble1(std::string s1, std::string s2) {
		return is_scramble(s1.begin(), s1.end(), s2.begin());
	}
private:
	typedef std::string::iterator iterator;
	bool is_scramble(iterator first1, iterator last1, iterator first2){
		auto length = std::distance(first1, last1);
		auto last2 = std::next(first2, length);

		if(length == 1)
			return *first1 == *first2;

		for(int i=0; i<length; ++i)
			if(is_scramble(first1, first1+i, first2) && is_scramble(first1+i, last1, first2+i)
		    	|| is_scramble(first1, first1+i, last2-i) && is_scramble(first1+i, last1, first2))
					return true;
		return false;
	}
#endif
#ifdef _USE_METHOD_2_
//method 2, DP, O(n^4)
public:
    bool is_scramble2(std::string s1, std::string s2) {
		size_t len_s1 = s1.length();
		size_t len_s2 = s2.length();
	
		if(len_s1 != len_s2)
			return false;
	
		std::vector<std::vector<std::vector<bool> > > 
		vec(len_s1+1, std::vector<std::vector<bool> >(len_s1, std::vector<bool>(len_s1, false)));
	
		for(int i=0; i<len_s1; ++i)
			for(int j=0; j<len_s1; ++j)
				vec[1][i][j] = s1[i] == s2[j];
	
		for(int n=2; n<=len_s1; ++n){
			for(int i=0; i<=len_s1-n; ++i){	
				for(int j=0; j<=len_s1-n; ++j){
					for(int k=1; k<n; ++k){
						if(vec[k][i][j] && vec[n-k][i+k][j+k]
							|| vec[k][i][j+n-k] && vec[n-k][i+k][j]){
							vec[n][i][j] = true;
							break;
						}
	
					}
				}	
			}
		}
	
		return vec[len_s1][0][0];
	}
#endif
#ifdef _USE_METHOD_3_
//method 3, recursion + prune
public:
	bool is_scramble(std::string s1, std::string s2) {
		return is_scramble(s1.begin(), s1.end(), s2.begin());
	}
private:
	typedef std::string::iterator iterator;
	bool is_scramble(iterator first1, iterator last1, iterator first2){
		auto length = std::distance(first1, last1);
		auto last2 = std::next(first2, length);

		if(length == 1)
			return *first1 == *first2;

		int A[26];   //why array not out of range, only for 26 characters
		std::fill(A, A+26, 0);
		for(int i=0; i<length; ++i){ 
			++A[*(first1+i)-'a'];
			std::cout<<(*(first1+i)-'a')<<' ';
		}
		for(int i=0; i<length; ++i)
			--A[*(first2+i)-'a'];
		for(int i=0; i<26; ++i)
			if(A[i] != 0)
				return false;

		for(int i=0; i<length; ++i)
			if(is_scramble(first1, first1+i, first2) && is_scramble(first1+i, last1, first2+i)
		    	|| is_scramble(first1, first1+i, last2-i) && is_scramble(first1+i, last1, first2))
					return true;
		return false;
	}
#endif
//method 4, recursion + cache(map)
public:
	bool is_scramble(std::string s1, std::string s2) {
		cache.clear();
		return is_scramble(s1.begin(), s1.end(), s2.begin());
	}
private:
	typedef std::string::const_iterator iterator;
	std::map<std::tuple<iterator, iterator, iterator>, bool> cache;   //using map to cache

	bool is_scramble(iterator first1, iterator last1, iterator first2){
		auto length = std::distance(first1, last1);
		auto last2 = std::next(first2, length);

		if(length == 1)
			return *first1 == *first2;

		for(int i=0; i<length; ++i)
			if(get_or_update(first1, first1+i, first2) && get_or_update(first1+i, last1, first2+i)
		    	|| get_or_update(first1, first1+i, last2-i) && get_or_update(first1+i, last1, first2))
					return true;
		return false;
	}
	bool get_or_update(iterator first1, iterator last1, iterator first2){
		auto key = make_tuple(first1, last1, first2);
		auto pos = cache.find(key);

		return pos != cache.end() ? pos->second : (cache[key] = is_scramble(first1, last1, first2));
	}
};

//method 5, recursion+cache(unordered_map)
typedef std::string::const_iterator iterator;
typedef std::tuple<iterator, iterator, iterator> key;

namespace std
{

template <> struct hash<key> {   
	size_t operator()(const key& x) const {
		::iterator first1, last1, first2;
		std::tie(first1, last1, first2) = x;

		int result = *first1;
		result = result * 31 + *last1;
		result = result * 31 + *first2;
		result = result * 31 + *(std::next(first2, std::distance(first1, last1)));
		return result;
	}
};

}

class solution {
public:
	std::unordered_map<key, bool> cache;
	
	bool is_scramble(std::string s1, std::string s2) {
		cache.clear();
		return is_scramble(s1.begin(), s1.end(), s2.begin());
	}
private:
	bool is_scramble(iterator first1, iterator last1, iterator first2){
		auto length = std::distance(first1, last1);
		auto last2 = std::next(first2, length);

		if(length == 1)
			return *first1 == *first2;

		for(int i=0; i<length; ++i)
			if(get_or_update(first1, first1+i, first2) && get_or_update(first1+i, last1, first2+i)
		    	|| get_or_update(first1, first1+i, last2-i) && get_or_update(first1+i, last1, first2))
					return true;
		return false;
	}
	bool get_or_update(iterator first1, iterator last1, iterator first2){
		auto key = make_tuple(first1, last1, first2);
		auto pos = cache.find(key);

		return pos != cache.end() ? pos->second : (cache[key] = is_scramble(first1, last1, first2));
	}
};

int main()
{
	std::string s1 = "great";
	std::string s2 = "rgeat";

	solution sl;
	assert(sl.is_scramble(s1, s2));
	
	return 0;
}

unorder_map为什么选用31做哈希,原因如下:

A.31是一个素数,素数作用就是如果我用一个数字来乘以这个素数,那么最终的出来的结果只能被素数本身和被乘数还有1来整除!。(减少冲突)

B.31可以 由i*31== (i<<5)-1来表示,现在很多虚拟机里面都有做相关优化.(提高算法效率)

C.选择系数的时候要选择尽量大的系数。因为如果计算出来的hash地址越大,所谓的“冲突”就越少,查找起来效率也会提高。(减少冲突)

D.并且31只占用5bits,相乘造成数据溢出的概率较小。


汇川H5U PLC 实现直线插补、圆弧插补、直线圆弧混合连续插补 使用汇川H5UPLC实现直线插补,圆弧插补,直线圆弧混合路径插补,通过示教可以走出复杂的路径,仅供参考学习。 阅读详情

相关推荐

uniapp+ucharts折线图toolTip不显示?别慌,手把手教你用showToolTip方法精准修复

本文详细解析了uniapp+ucharts折线图中toolTip不显示的常见问题,提供了showToolTip方法的精准修复方案。从底层原理到实战代码,帮助开发者解决触摸事件冲突、坐标计算偏差等问题,确保折线图交互提示功能稳定运行。

weixin_30316097的博客 404

[LeetCode] Scramble String

Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively. Below is one possible representation of s1 = "great": great / ...

weixin_33739627的博客 128

华为防火墙主备模式工作原理

防火墙主备模式下,备墙的工作状态

weixin_67050107的博客 2142

[Leetcode]87. Scramble String

[Leetcode]87.Scramble String 本题难度: Hard Topic: divide and conquere Description Given a strings1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursivel...

weixin_30856965的博客 96

FSMC驱动LCD显示屏学习2

液晶显示器,简称 LCD(Liquid Crystal Display)相对于上一代 CRT 显示器 (阴极射线管显示器),LCD显示器具有功耗低、体积小、承载的信息量大及不伤眼的优点,因而它成为了现在的主流电子显示设备液晶是一种介于固体和液体之间的特殊物质,它是一种有机化合物,常态下呈液态,但是它的分 子排列却和固体晶体一样非常规则,因此取名液晶。

usjjjsj的博客 1698

【跳频通信】基于MATLAB的跳频通信系统仿真

同时,跳频通信也具有良好的抗干扰能力,即使有部分频点被干扰,仍能在其他未被干扰的频点上进行正常的通信。由于跳频通信系统是瞬时窄带系统,它易于与其他的窄带通信系统兼容,也就是说,跳频电台可以与常规的窄带电台互通,有利于设备的更新。跳频是最常用的扩频方式之一,其工作原理是指收发双方传输信号的载波频率按照预定规律进行离散变化的通信方式,也就是说,通信中使用的载波频率受伪随机变化码的控制而随机跳变。从通信技术的实现方式来说,“跳频”是一种用码序列进行多频频移键控的通信方式,也是一种码控载频跳变的通信系统。

FPGA/MATLAB学习教程/源码/项目合作开发 6267

LeetCode 87 scramble-string

LeetCode 87 一开始我的思路是把所有的scramble的strings都求出来,然后看看另外一个是否在里面。快速可以优化的地方就是记住已经求过的scramble的strings。 代码相对比较容易,每次把string都拆成两部分,然后求scramble的strings,再组合在一起: def isScrambleSlow(self, s1: str, s2: str) ->...

frankguodongchen的博客 181

关于 ABAP OPEN SQL 的动态 WHERE 条件和 Dynamic Selections

ABAP动态查询技术解析 本文介绍了ABAP中实现灵活数据库查询的动态选择技术,通过FREE_SELECTIONS函数组实现用户自定义查询条件。核心内容包括: 传统固定WHERE条件的局限性,无法满足业务多变需求 Dynamic Selections机制的工作原理,使用FREE_SELECTIONS_INIT初始化、FREE_SELECTIONS_DIALOG交互 完整Demo程序演示如何构建通用表数据浏览器: 用户输入表名后校验权限 调用动态选择函数生成条件 动态拼接WHERE子句执行查询 使用CL_SA

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 678

LeetCode87 Scramble String

LeetCode87 Scramble String问题来源LeetCode87问题描述 Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively. Below is one possible representat

yanqinghe123的专栏 411

开源数字人、虚拟直播部署教程

对,你无看错,是欧美的。在直播带货案例里,我们把模型导入到ue4,我们给模型在ue4里预设了四个动作(站着、站着说话、坐着、坐着说话),三个表情(平静、开发、愤怒),三个镜头(全局、近矩说话、看显示器播放商品展示)。我们只需要把目标主播的直播给录制下来,提取样本数据,然后训练一个从粉丝的不同刺激的组合,到主播的不同响应方式的多元逻辑回归的数学模型参数即可。

南七小僧的学海无涯 4564

SAP 标准 CDS View 到底能不能用 CDS Extension View 扩展,我们在项目里应该这样判断

文章摘要:判断SAP标准CDS视图(如A_PRODUCT)能否扩展字段,不能仅凭命名或@Metadata.allowExtensions判断,需检查DDL源码中的@AbapCatalog.viewEnhancementCategory值。#PROJECTION_LIST允许扩展字段,#NONE则禁止。聚合视图需额外包含#GROUP_BY,UNION视图需#UNION。CDS View Extension用于新增字段,Metadata Extension仅用于添加注解。在ABAP Cloud环境中还需检查AP

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 102

Leetcode 87 Scramble String

思路:我成功地写出了如果只修改一次的话,判断是否是scramble string的方法。但很可惜,这边修改的节点可以是多个,我觉得我这种方法继续写下去应该是可以实现题目要求的,但是我想了好久,不会哈哈哈。我猜应该用recursive的方法来继续写下去?我也不太确定。但是我真的是太不喜欢recursive方法,哎但是,好像dfs,dp都和recursion有着一点关系。真得好好练练。我看了high votes answer,发现人家也是recursive的方法。真的我看懂他这个代码都花了一个多小时吧。烦死了.

GoodJobJasper的博客 266

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

#87 Scramble String

Description We can scramble a string s to get a string t using the following algorithm: If the length of the string is 1, stop. If the length of the string is > 1, do the following: Split the string into two non-empty substrings at a random index, i.e.

YY_Tina的博客 189

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

leetcode 87. Scramble String 二分法

leetcode 87. Scramble String public class Solution { public static void main(String[] args){ String s1 = "ab"; String s2 = "ba"; Solution s = new Solution(); System.out.println(s.isScr

独钓寒江雪 384

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

[leetcode] 87. Scramble String

Description Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively. Below is one possible representation of s1 = “great”: great / gr ...

Learning from the mistakes 285

LeetCode: 87. Scramble String

LeetCode: 87. Scramble String 题目描述 Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively. Below is one possible representation of s1 =...

杨领well的专栏 844

LeetCode87——Scramble String

LeetCode87——Scramble String 目前递归解决的方法

上善若水 537

【Leetcode】87. Scramble String

题目地址: https://leetcode.com/problems/scramble-string/ 给定两个字符串s1s_1s1​和s2s_2s2​,允许将s1s_1s1​做以下操作: 1、若s1=x+ys_1=x+ys1​=x+y,xxx和yyy都是s1s_1s1​的非空子串,那么可以将s1s_1s1​变成y+xy+xy+x; 2、在1的基础上,对xxx和yyy继续做与111相同操作。也就是说,一旦进行了1的操作,还可以继续将xxx和yyy重新视为s1s_1s1​来做分割交换的操作。 问s1s_1s

数学、算法爱好者的博客 219

Leetcode#87 Scramble String

原题地址 两个字符串满足什么条件才称得上是scramble的呢? 如果s1和s2的长度等于1,显然只有s1=s2时才是scramble关系。 如果s1和s2的长度大于1,那么就对s1和s2进行分割,划分成两个子问题分别处理。 如何分割呢?当然不能任意分割。假设分割后s1变成了s11和s12,s2变成了s21和s22,那么只有2种分割方式: 1. s11.length...

dicui3114的博客 111

LeetCode String 87 Scramble String

87. Scramble String Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively. Below is one possible representation of s1 = “great”: To scramb...

Yi Jiao's Blog 164

【To Understand !!! DP or 递归】LeetCode 87. Scramble String

LeetCode 87. Scramble String 参考链接:[1]https://blog.csdn.net/makuiyu/article/details/44926439 [2]http://www.cnblogs.com/grandyang/p/4318500.html Solution1: 递归 class Solution { public: bool isSc...

Allenlzcoder的博客 310

87. Scramble String Leetcode Python

Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively. Below is one possible representation of s1 = "great": great / \ gr

hyperbolechi的专栏 845
上一篇: 一致性哈希算法C++模板实现
下一篇: 287. Find the Duplicate Number(链表判环)
FreeeLinux
博客等级 码龄11年 421粉丝 356原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值