LeetCode 161 One Edit Distance

告别死记硬背!用业务场景驱动理解SAP PS OPSA参数文件配置 本文通过制造业新产品研发项目案例,详细解析SAP PS模块中OPSA参数文件配置的实际应用。从项目立项、WBS分解到研发物料管理,系统讲解关键配置项的业务价值,帮助用户告别死记硬背,实现业务场景驱动的参数配置学习。特别适合制造业项目管理人员提升SAP PS配置效率。 阅读详情

Problem:

Given two strings S and T, determine if they are both one edit distance apart.

Analyse:

delete, add, replace 都是one edit distance.
delete 和 add: 两个string 的长度相差一
replace: 两个string的长度相同

伪代码:

string s, t
n <- s.length
m <- t.length

if n - m >= 2 || m-n >= 2
return false
if n-m = 1 || m-n =1
return isOneChangeDitance()
if n-m=0
return isOneReplaceDistance()

下面讨论一些细节
isOneChangeDitance()

s: z x c v b
l
t: z x v b
s

对于这个列子,可以看出delete s 的一个char或者给 t add一个char 就相同. 所以是One Edit Distance.
In this problem, we can create two pointer. One is long string’s pointer: l. Another one is short string’s pointer: s. Both of two pointers go with the same pace to scan the string. When they point to the same character, both of them move to the next character. When they point to the different character, the long pointer move forward and the short one stay. After that, they go with the same pace to check what’s going on in the following parts of the string.

isOneReplaceDistance()

s: z x c b
l
t: z x v b
s

In thsi scenario, we also make l pointer and s pointer go with the same pace. When they find the different character, count it and move forward. If the counting number is larger than 1, return false.

其他

  1. 当两个string完全相同时,也不算做 One Edit Distance
  2. 注意如何建立两个指针同时扫面Sting
  3. 还有一些Conner Situation

code(Java)

public class Solution1 {

	public static boolean isOneEditDistance(String s, String t) {
		
		if(s == null && t == null) return true;
		if(s == null || t == null) return false;
		
		int n = s.length();
		int m = t.length();
		
		
		if (n - m >= 2 || m - n >= 2) return false;
		
		if (n - m == 1) {
			return isOneChangeDistance(s,t);
		}
		
		if ( m - n == 1) {
			return isOneChangeDistance(t,s);
		}
		
		if ( n - m == 0) {
			return isOneReplaceDistance(s,t);
		}
		
		return false;
	}
	
//	default string s is longer than string t
	public static boolean isOneChangeDistance(String s, String t) {
		
		int count = 0;
		//扫描长String比较安全,扫描短的容易out of bound
		for (int i=0, j=0; i<s.length(); i++) {
			if (s.charAt(i) == t.charAt(j)) {
				j++;
			}else {
				count++;
			}
		}	
		if (count == 1) return true;
		else return false;

	}
	
	
	public static boolean isOneReplaceDistance(String s, String t) {
		
		int count = 0;
		for (int i=0; i<t.length(); i++) {
			if (s.charAt(i) != t.charAt(i)) {
				count++;
			}		
		}
		if (count == 1) return true;
		else return false;
	}
	
	
	
	public static void main(String[] args) {
		
		String s = "";
		String t = "";		
		System.out.println(isOneEditDistance(s,t));
		
	}		
}



RK3588 C-PHY摄像头驱动升级踩坑记:从‘Only CSI2 supported’报错到成功取流 本文详细记录了在RK3588平台上调试C-PHY摄像头驱动的全过程,从‘Only CSI2 supported’报错分析到成功取流。内容涵盖C-PHY与CSI-2协议差异、SDK版本对比、V4L2框架下的bus-type解析机制,以及硬件排查与寄存器调优实战经验,为嵌入式Camera驱动工程师提供宝贵参考。 阅读详情

相关推荐

PD虚拟机网络初始化失败的权限修复指南

本文针对Parallels Desktop虚拟机常见的“网络初始化失败”问题,提供了详细的权限修复指南。通过分析问题根源,指导用户安全备份并修改关键的`network.desktop.xml`和`dispatcher.desktop.xml`配置文件,以恢复PD虚拟机的网络连接。文章还包含了修复后的验证步骤及预防措施,帮助用户彻底解决并避免此类权限问题。

qqq44的博客 858

LeetCode—161. One Edit Distance

Binary Tree Upside Down思路:其实分类讨论更容易一次过,考虑长度相等和差1的情况,特别注意,s.equals(t)是false GitHub地址:https://github.com/corpsepiges/leetcode 点此进入如果可以的话,请点一下star,谢谢。 public class Solution {

徐玄清的专栏 694

HALCON基于描述符的模板匹配(未标定)

HALCON基于不标定描述符的模板匹配

king_linj的博客 902

LeetCode 161. One Edit Distance--Python,Java,C++解法

LeetCode题解专栏:LeetCode题解 我做的所有的LeetCode的题目都放在这个专栏里,大部分题目Java和Python的解法都有。 欢迎大家关注我的专栏。 此题链接:One Edit Distance - LeetCode 这道题目进阶版本Edit Distance - LeetCode 文章地址:LeetCode 72. Edit Distance - zhangpeterx的...

个人博客 1055

超全!!snowboy语音唤醒(树莓派4b)

通过snowboy进行树莓派的语音唤醒

crimaster1024的博客 8746

Vivado 2021.1 实战:手把手教你用IEEE1735 V2加密你的Verilog源码(附完整TCL命令)

本文详细介绍了在Vivado 2021.1中使用IEEE1735 V2标准加密Verilog源码的全流程,包括许可证申请、密钥文件配置、TCL命令执行及加密后验证。通过实战步骤和完整TCL命令,帮助开发者有效保护FPGA设计知识产权,确保核心算法安全。

weixin_42706667的博客 202

[LeetCode]161. One Edit Distance

原题链接:https://leetcode.com/problems/one-edit-distance/ 这道题目及变种多次在各大公司的面经中出现过。我在面snapchat的时候也遇到过这道题目。题目是说我们要求给定2个输入字符串S和T,要求判断S和T是不是只有一个字符只差。这里One Edit Distance意思就是你改动其中一个字符串的1个字符,就会变成另一个字符串。这里的改动包括增加1

foolman 656

海思Hi3516CV610开发实战:在Ubuntu 22.04上从零构建嵌入式Linux开发环境

本文详细介绍了在Ubuntu 22.04上为海思Hi3516CV610开发板搭建嵌入式Linux开发环境的完整流程。从虚拟机配置、系统安装到基础环境设置,提供了实用技巧和常见问题解决方案,帮助开发者高效构建适用于智能视觉处理的开发环境。

weixin_29197699的博客 517

【LeetCode】161. One Edit Distance

LeetCode161 传送门 解法: 推荐解法和我的解法看似类似,时间、空间复杂度非常接近,但实则简洁很多。究其原因,推荐方法中采用了分段的思想。这种分段的思想很适合于字符串问题。 Python源码: Runtime:24 ms, faster than28.87%ofPythononline submissions forOne Edit Distance. Me...

weixin_42344158的博客 282

MFC实现图书管理系统(附完整源码)

MFC实现图书管理系统(附完整源码)

希望我的博客,能帮上你解决学习中工作中所遇到的问题 814

软考嵌入式 第五讲 嵌入式Linux系统技术

5.1 inittab配置文件 Linux实时操作系统开机引导时首先启动内核,由内核检查和初始化硬件设备,载入设备的驱动程序模块,安装root文件系统,然后内核将启动一个名为init的进程,它是系统运行的第一个进程,进程号为1。在init运行完成并启动其他必要的后续进程后,系统开始运行,引导过程结束。 在任何时候,可以在文件inittab中添加新的记录项。重新检查inittab文件时,可以通过命令:init q/ Q使init进程立即重新读取并处理文件inittab。 5.1.1 inittab文件记录

Leon的博客 527

leetcode 161: One Edit Distance

One Edit Distance Total Accepted: 709 Total Submissions: 3097 Given two strings S and T, determine if they are both one edit distance apart. [分析] delete, add, replace 三种都是 One edit dista

西施豆腐渣 5900

HITECH海泰克触摸屏如何使用串口进行程序的下载和上传(拨码设置)以及离散量报警相关设定?

HITECH海泰克触摸屏如何使用串口进行程序的下载和上传(拨码设置)以及离散量报警相关设定? 首先,我们进行触摸屏一侧的设置,如下图所示: 触摸屏背后有拨码开关,当我们需要上传或下载程序时,需要将7#开关拨到上面; 左侧是DC24V电源接口; 下方是COM1、COM2和COM3通信端口,选择我们需要的端口后,插上通信电缆,拔掉24V电源,然后重新上电; 然后,屏幕会进入如下图所示界面,此时显示当前选择的端口为COM2,我们点击F2“config”,进入设置界面, 可以看到COM2端口是“Enabled”

Robot_PLC_HMI_Automation 3万+

Leetcode 161 One Edit Distance

思路:分为三个部分来做,delete,replace,insert。 delete很容易,只需要把长度大的那个string遍历remove每个元素,每remove一个元素,就和另一个string比较是否相等,如果想等就返回true。 replace也很容易,此时两个string必定是相等长度的,因为本题我们只修改s,以符合t,所以我们只需要将t中的每一个元素挨个替换s中的每一个元素,每替换一次,就进行一次比较,如相等,返回true。 insert,此时肯定是s比t长度小1,insert一个字母后两者相等。.

GoodJobJasper的博客 322

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

leetcode[161] One Edit Distance

判断两个字符串的编辑距离是不是1. 关于编辑距离可以参见之前有一题leetcode[72] Edit Distance 思路: 如果字符串相差2个以及以上长度,那么肯定不止1,直接false 如果字符串长度相等,那么判断对应位置不同的字符数是不是1即可。 如果字符串长度相差1,那么肯定是要在长的那个串删掉一个,所以两个字符串一起加加,一旦遇到一个不同,那么剩下的子串就要是一样,...

175

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

【Leetcode】161. One Edit Distance

题目地址: https://leetcode.com/problems/one-edit-distance/ 给定两个字符串sss和ttt,问sss可否由下列三种变换变为ttt: 1、在sss中插入一个字符; 2、在sss中删除一个字符; 3、在sss中替换一个字符。 如果可以就返回true,否则返回false。 首先排除掉sss与ttt长度差大于等于222或者sss和ttt相等的情况,这两种情况...

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

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

LeetCode String 161 One Edit Distance

161. One Edit Distance Given two strings s and t, determine if they are both one edit distance apart. Note: There are 3 possiblities to satisify one edit distance apart: Insert a character into s to g...

Yi Jiao's Blog 171

LeetCode 161. One Edit Distance (Java版; Medium)

welcome to my blog LeetCode 161. One Edit Distance (Java版; Medium) 题目描述 Given two strings s and t, determine if they are both one edit distance apart. Note:  There are 3 possiblities to sa...

littlehaes的博客 283

[LeetCode161] One Edit Distance

Given two strings S and T, determine if they are both one edit distance apart.Hide Company Tags Uber Facebook Hide Tags String Hide Similar Problems (H) Edit Distance 所谓Edit distance, 一次delete, insert

MoM 352

[leetcode] 161. One Edit Distance @ python

原题 Given two strings s and t, determine if they are both one edit distance apart. Note: There are 3 possiblities to satisify one edit distance apart: Insert a character into s to get t Delete a charac...

闲庭信步 466

[Leetcode] 161. One Edit Distance 解题报告

题目: Given two strings S and T, determine if they are both one edit distance apart. 思路: One Edit Distance意味着一个字符串s可以通过删除,增加或者修改其中的一个字符变成另外一个字符串t。因此我们可以根据s和t的长度分别处理:如果两者长度相同,则判断s和t是否仅仅有一个字符不相同;如果t的

魔豆(Magicbean)的博客 814

LeetCode 161. One Edit Distance

#include #include using namespace std; /* Given two strings S and T, determine if they are both one edit distance apart. */ bool isOneEditDistance(string s, string t) { int sSize = s.size();

ActiveCoder的博客 393

Leetcode-161.One Edit Distance

Problem Description: Given two strings S and T, determine if they are both one edit distance apart.Analysis: Ref: http://www.cnblogs.com/jcliBlogger/p/4602455.html For the one edit distance, you can

Tigers Den 350

Obsidian 同步与备份实战:WebDAV + Git + 冷备份组合方案

在知识管理场景中,笔记的同步与备份是高频需求。许多用户选择本地优先的 Markdown 工具管理个人知识库,但多设备访问和历史回溯仍是痛点。同步保证多端一致,备份防止数据丢失,版本控制实现回滚。WebDAV 协议提供跨平台文件读写能力,配合 Remotely Save 插件可实现定时同步;Git 对纯文本文件具有优秀的差异追踪能力,适合做历史版本记录;再辅以定期压缩快照,形成三层保护。无论个人笔记库还是团队知识库,这套方案都能在免费前提下提供稳定可靠的数据安全保障,有效解决 Obsidian 等 Markd

weixin_33768481的博客 411

LeetCode 161.One Edit Distance

Given two strings S and T, determine if they are both one edit distance apart.s思路: 1. 求两个字符串的distance和Edit Distance一样:增加一个字符、减少一个字符、修改一个字符。所以,先判断长度,如果长度差>1,则不是one edit distance;如果长度差==1,则两个string只有一个字

xinqrs01的博客 349

LeetCode 161. One Edit Distance(java)

Given two strings S and T, determine if they are both one edit distance apart. 注意:当s和t完全相同时,需要返回false.最快的解法:先调整s和t的长度,使得s的长度小于t,解法中的解决方法很巧妙,通过交换参数,再次调用函数实现~。然后开始判断m和n的长度,如果相差大于1则返回false。遍历两个字符串,当出现两个字

katrina95的博客 420
上一篇: Leetcode 253: meeting room
下一篇: LeetCode 138 Copy List with Random Pointer
Opium_Z
博客等级 码龄8年 0粉丝 27原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值