87. Scramble String

【Godot】构建可维护的游戏工程 —— 项目代码组织结构 本文系统梳理了Godot引擎项目组织原则与架构模式,提出场景中心化、命名规范一致性和资源隔离三大核心原则。推荐按功能模块划分目录结构(如scenes/、entities/、systems/),采用snake_case命名避免跨平台问题,并通过.gdignore优化资源管理。文章详细解析了自包含场景设计、信号驱动解耦等架构技巧,以及团队协作中的版本控制策略,强调通过模块化设计平衡一致性与实用性。最终目标构建清晰可维护的项目结构,使资源定位和功能扩展更加高效。(148字) 阅读详情

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,相乘造成数据溢出的概率较小。


手把手教你学veriolg(二十六)-- Verilog CIC 滤波器设计 目录 Verilog CIC 滤波器设计1. CIC 滤波器的基本原理2. Verilog 实现3. 说明4. 测试激励5. 总结 CIC(Cascade-Integrator-Comb)滤波器是一种特殊的数字滤波器,常用于多速率信号处理中,尤其是用于信号的上采样(插值)和下采样(抽取)。CIC 滤波器的特点在于它具有简单的硬件实现、不需要乘法器(仅使用加法器和延迟元件)、且具有线性相位特性。然而,CIC 滤波器的缺点是它会产生较大的量化误差,因此在设计时需要特别注意字长的选择以避免溢出。1. CIC 滤波 阅读详情

相关推荐

什么是PMOS?什么是NMOS?两者有什么区别?

这个电压差被称为阈值电压(Vth),通常为0.7V至2V(低压NMOS)或4V至10V(功率NMOS)。当Vgs(栅极-源极电压)大于Vth时,沟道中的电子被吸引到栅极下方,形成导电通路,使电流可以从漏极流向源极。NMOS与PMOS的结构类似,都由三大部分组成:栅极(Gate)、源极(Source)和漏极(Drain)。由于NMOS在开启时,电子是主要的载流子,电子的迁移率比空穴高,因此NMOS通常具有更低的导通电阻(Rds(on)),这使其成为高速开关电路中的首选。它的沟道由电子(负载子)传导。

硅农深芯的博客 6507

[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

利用树莓派制作智能音箱

利用树莓派制作智能音箱

qq_61803022的博客 1792

[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的博客 98

WindTerm 安装使用教程

WindTerm是一款Github上开源的 SSH 终端工具,它是完全可以比肩MobaXterm工具的。

m0_69576880的博客 4083

关于RT-Thread中PWM无法正常输出的学习

按照官方的PWM配置,并没有输出PWM,网上有比较多的办法,试了很多,有些还是不能实现输出,这里做个记录。记录自己完成PWM输出的过程,以及修改的地方。 关于STM32CubeMX配置就不多说了,网上有很多。 首先必定是按照流程来,一定一定按照流程来!!! 需要注意的是加上通道数!!!! 这是流程上没有的,也是RTT的一点小BUG吧 配上board.c中添加的代码,我用的是PA2定时2的通道3,需要使用的朋友修改对应定时器和GPIO! void HAL_TIM_Base_MspInit(TIM_Han

weixin_42566346的博客 3562

LeetCode 87 scramble-string

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

frankguodongchen的博客 182

一个代码循环计算水在石墨烯表面的接触角

石墨烯接触角

Rockyoung 2588

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的专栏 412

作为一名爬虫人如何实现千万级数据爬取?

爬虫门槛不高,高就高在往后余生的每一次实操都随时会让你崩溃!Bro

吴秋霖的博客 1万+

YOLOv11的代数不变量解释:Syzygy模分析特征重要性,用交换代数揭示卷积核的语义相关性

本文提出了一种基于代数几何与交换代数的创新方法,特别是运用Syzygy模理论,对YOLOv11目标检测算法的卷积核语义相关性进行数学解释。研究揭示了YOLO系列算法演进背后的代数结构特征,建立了网络组件与多项式环、理想簇等代数概念的对应关系。通过构建分层的准同构代数系统,分析了YOLOv11在不同尺度下保持语义不变性的数学本质。文章系统阐述了Syzygy模在CNN特征冗余分析、跨层依赖关系建模和语义聚类中的应用,并提出了适用于动态稀疏训练的改进算法。该理论框架为深度神经网络的解释性研究提供了新的数学工具,同

本博客聚焦 YOLOv11 全流程落地,涵盖架构优化、数据集处理、训练技巧与多场景部署,兼及国产数据库、Java 开发与 AI 模型应用,内容兼顾理论与工程实践,为开发者提供系统干货,助力高效提升技术能力。 1288

Leetcode 87 Scramble String

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

GoodJobJasper的博客 266

分布式爬虫架构实战:Scrapy+RabbitMQ+浏览器池,百万级数据抓取成本直降60%(附架构图+源码)

任务调度瓶颈:Redis 作为消息队列,不支持复杂任务优先级,高并发下容易消息堆积,且单点故障会导致全量任务丢失;资源浪费严重:每个爬虫节点每次爬取动态页面都启动新浏览器,启动耗时3-5秒,CPU 占用率高达80%+,单机最多同时跑3个浏览器;扩展性差:新增节点需要手动同步任务队列,节点忙闲不均,无法根据任务量动态分配资源。# 从settings读取RabbitMQ配置# 注册信号:爬虫关闭时关闭RabbitMQ连接"""启动时建立RabbitMQ连接"""

专注于Python爬虫开发,分享爬虫技巧、项目实战与反爬经验,使用Scrapy、BeautifulSoup等工具,解决数据抓取难题。 1624

#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的博客 190

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

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

独钓寒江雪 386

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

[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 287

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

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的专栏 846

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 166

【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的博客 311

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、付费专栏及课程。

余额充值
⌂ 换网址