当前位置: 首页 > news >正文

算法练习-LeetCode1071. Greatest Common Divisor of Strings

题目地址:LeetCode - The World's Leading Online Programming Learning Platform

Description: For two strings s and t, we say "t divides s" if and only if s = t + ... + t (i.e., t is concatenated with itself one or more times).

Given two strings str1 and str2, return the largest string x such that x divides both str1 and str2.

Example 1:

Input: str1 = "ABCABC", str2 = "ABC"
Output: "ABC"

Example 2:

Input: str1 = "ABABAB", str2 = "ABAB"
Output: "AB"

Example 3:

Input: str1 = "LEET", str2 = "CODE"
Output: ""

 这道题一开没有想出来就直接放弃看别人的做法,看完之后才发现难怪自己想不粗来。真的不看别人的思路,直接看代码都看不懂😭。

参考的之后写的解题代码如下:

class Solution {public String gcdOfStrings(String str1, String str2) {if(!(str1+str2).equals(str2+str1)){return "";}int gcd = getGcd(str1.length(),str2.length());return str1.substring(0,gcd);}public int getGcd(int a , int b){if(b == 0) return a;return getGcd(b,a%b);}}

思路:

(1)Corner Case:两个String 要有 Greatest Common Divisor(GCD)的话,左边右边拼接起来都应该是完全一样的,不能存在不同的情况:

"ABCEABCEABCE" + "ABCE" = "ABCEABCEABCEABCE"

"ABCE" + "ABCEABCEABCE" = "ABCEABCEABCEABCE"

如果存在不同的情况,就不存在最大GCD:

"ABAB" + "BB" = "ABABBB"

"BB" + "ABAB" = "BBABAB"

(2)存在GCD的情况下,如下其GCD的长度是两个String长度的最大公因子:

"ABCEABCEABCE" + "ABCE" = "ABCEABCEABCEABCE"

               12                        4                 ->      4 (最大公因子 = GCD长度)

"ABCE" + "ABCEABCEABCE" = "ABCEABCEABCEABCE"

通过递归找到GCD长度:

 public int getGcd(int a , int b){if(b == 0) return a;return getGcd(b,a%b);}

然后通过找到的GCD长度substring其中任意一个string就能找到GCD。

http://www.lryc.cn/news/98511.html

相关文章:

  • Nuget不小心用sudo下载后怎么在user里使用
  • 软件测试技能大赛环境搭建及系统部署报告
  • 浅谈现代通信技术
  • windows环境下adb 下载和配置,连接手机。
  • [STL]list使用介绍
  • k8s服务发现之第五弹--使用 Service 连接到应用
  • SAP ABAP 自定义表数据导入
  • 目标检测识别——大恒(DaHeng)相机操作与控制编程
  • 国标GB28181视频监控平台EasyGBS视频无法播放,抓包返回ICMP是什么原因?
  • 如何正确使用npm常用命令
  • 无人机影像配准并发布(共线方程)
  • openGauss学习笔记-23 openGauss 简单数据管理-时间/日期函数和操作符
  • C++OpenCV(7):图像形态学基础操作
  • Appium+python自动化(二十二)- 控件坐标获取(超详解)
  • Tensorflow benchmark 实操指南
  • 【linux】调试工具介绍
  • 2.获取DOM元素
  • flask中redirect、url_for、endpoint介绍
  • 《MySQL》第十二篇 数据类型
  • Python与OpenCV环境中,借助SIFT、单应性、KNN以及Ransac技术进行实现的图像拼接算法详细解析及应用
  • 苍穹外卖Day01项目日志
  • Netty学习(二)
  • ReactRouterv5在BrowserRouter和HashRouter模式下对location.state的支持
  • Aerotech系列文章(3)运动设置命令Motion Setup Commands
  • 线性神经网络——softmax 回归随笔【深度学习】【PyTorch】【d2l】
  • 【Nodejs】Node.js开发环境安装
  • 梅尔频谱(Mel spectrum)简介及Python实现
  • 【数据结构】实验六:队列
  • 【Linux线程】第一章||理解线程概念+创建一个线程(附代码加讲解)
  • Android进阶之微信扫码登录