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

算法通关村第十二关|黄金挑战|最长公共前缀字符串压缩

1.最长公共前缀

原题:力扣14.

1.从前到后比较每个字符串的同一个位置。

public String longestCommonPrefix(String[] strs) {if (strs == null || strs.length == 0) {return "";}int length = strs[0].length();int count = strs.length;for (int i = 0; i < length; i++) {char c = strs[0].charAt(i);for (int j = 1; j < count; j++) {if (i == strs[j].length() || strs[j].charAt(i) != c) {return strs[0].substring(0, i);}}}return strs[0];
}

2.将完整的字符串进行比较得到公共前缀。然后遍历每个字符串,不断缩小这个公共前缀,遍历结束后得到的就是最长的公共前缀。

public String longestCommonPrefix(String[] strs) {if (strs == null || strs.length == 0) {return "";}String prefix = strs[0];int count = strs.length;for (int i = 1; i < count; i++) {prefix = longestCommonPrefix(prefix, strs[i]);if (prefix.length() == 0) {break;}}return prefix;
}public String longestCommonPrefix(String str1, String str2) {int length = Math.min(str1.length(), str2.length());int index = 0;while (index < length && str1.charAt(index) == str2.charAt(index)) {index++;}return str1.substring(0, index);
}

2.字符串压缩问题

原题:力扣443.

public int compress(char[] chars) {int n = chars.length;int write = 0, left = 0;for (int read = 0; read < n; read++) {if (read == n - 1 || chars[read] != chars[read + 1]) {chars[write++] = chars[read];int num = read - left + 1;if (num > 1) {int anchor = write;while (num > 0) {chars[write++] = (char)(num % 10 + '0');num /= 10;}reverse(chars, anchor, write - 1);}left = read + 1;}}return write;
}
public void reverse(char[] chars, int left, int right) {while (left < right) {char temp = chars[left];chars[left] = chars[right];chars[right] = temp;left++;right--;}
}

如果对您有帮助,请点赞关注支持我,谢谢!❤
如有错误或者不足之处,敬请指正!❤
个人主页:星不易 ❤
算法通关村专栏:不易|算法通关村 ❤

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

相关文章:

  • 池式组件 ----- Mysql连接池的原理实现
  • 1.自动化运维工具Ansible的安装
  • [个人笔记] Apache2.4配置TLS1.3安装openssl1.1.1
  • 解密Kafka主题的分区策略:提升实时数据处理的关键
  • GPT5大剧第二季开启,Sam Altman 重掌 OpenAI CEO 大权
  • Selenium 连接到现有的 Google Chrome 示例
  • EI级 | Matlab实现TCN-BiLSTM-Multihead-Attention多头注意力机制多变量时间序列预测
  • 基于安卓的2048益智游戏的设计与实现
  • 解决Linux Visual Studio Code显示字体有问题/Liunx下Visual Studio Code更换字体
  • CityEngine2023 根据shp数据构建三维模型并导入UE5
  • 修复电脑中缺失的VCRUNTIME140.dll文件的5个有效方法
  • 什么是PDN的交流阻抗?
  • FFmpeg之将视频转为16:9(横屏)或9:16(竖屏)(一)
  • Web安全漏洞分析-XSS(上)
  • MVCC多版本并发控制相关面试题整理
  • 02-鸿蒙学习之4.0todoList练习
  • springsecurity5.7.x和springsecurity6.x配置文件对比
  • brat文本标注工具——安装
  • 麒麟操作系统网桥配置
  • 禁奥义·SQL秘籍
  • 浅谈用户体验测试的主要功能
  • 2021年6月3日 Go生态洞察:Fuzzing技术的Beta测试
  • 全新Self-RAG框架亮相,自适应检索增强助力超越ChatGPT与Llama2,提升事实性与引用准确性
  • 句子相似度计算
  • 高级IO select 多路转接实现思路
  • C++学不会?一篇文章带你快速入门
  • 【加密相册】 隐私协议
  • 超越基础:释放 Systemd 的全部潜力【systemd 二】
  • Flask学习二:项目拆分、请求与响应、cookie
  • 6、Qt延时的使用