Implement strStr(字符串查找)
来源:互联网 发布:unity3d gui 编辑:程序博客网 时间:2024/06/04 19:57
重点内容对于一个给定的 source 字符串和一个 target 字符串,你应该在 source 字符串中找出 target 字符串出现的第一个位置(从0开始)。如果不存在,则返回 -1
先上一个粗暴的版本,思路较为简单,实现起来较为绕,不容易确保每种情况都正确。
测试用例:[null,null] [null,”“] [“”,null] [null,null] [“abide”,”e”] [“tartarget”,”target”]
public int strStr(String source, String target) { if (target == null || source == null || source.length() < target.length()) { return -1; } if (target.equals("")) { return 0; } char[] sArr = source.toCharArray(); char[] tArr = target.toCharArray(); int index = 0; int i = 0; int j = 0; for (; i < sArr.length;) { if (sArr[i] != tArr[j]) { //每次循环检查是否相同 j = 0; //一旦不同,target索引归零 if (sArr[i] != tArr[j]) { //检测不匹配的情况下,是否和target首字母相同 i++; index = i; continue; } index = i; i++; j++; continue; } i++; j++; if (j == tArr.length){ return index; } } return -1; }
上面的版本太过于蛮干,没有经过任何转换,因此接下来我们先对题目进行转换。
在source中查找target,如果source.length() < target.length()则肯定不会出现source包含target的关系。
如果source的前source.length() - target.length() + 1 个字母与target的首字母不匹配,则source中不包含target
测试用例同上。
public int strStr(String source, String target) { if (target == null || source == null) { return -1; } for (int i = 0; i < source.length() - target.length() + 1; i++){ int j = 0; for (; j < target.length(); j++) { if (source.charAt(i + j) != target.charAt(j)) { break; } } if (j == target.length()) { return i; } } return -1; }
0 0
- Implement strStr(字符串查找)
- LeetCode 28 Implement strStr()(子字符串查找)
- leetcode | Implement strStr() | 实现字符串查找函数
- LeetCode OJ 之 Implement strStr() (在字符串中查找字符串)
- Implement strStr() 字符串匹配(KMP)
- 28. Implement strStr()(String字符串匹配)
- 【字符串匹配】Implement strStr()
- 字符串匹配Implement strStr()
- leetcode---implement-strstr---字符串
- 【KMP&字符串匹配】Implement strStr()
- [LeetCode]Implement strStr() 字符串匹配
- leetcode 字符串匹配Implement strStr()
- [LeetCode] Implement strStr()[字符串hash]
- [leetcoide] 【字符串】28. Implement strStr()
- (LeetCode)Implement strStr() --- 匹配字符串
- Implement strStr()--字符串匹配_kmp_bkdHash
- #leetcode#Implement strStr()
- Implement strStr() (匹配字符串问题,哈希解法) 【leetcode】
- android 为什么不允许子线程访问UI
- MFC编写个简单学生管理信息程序
- input输入事件
- [ATL/WTL]_[初级]_[关于graphics.DrawImage绘图时显示不正常的问题]
- Bringing up interface eth0: Error: No suitable device found: no device found for connection 'System
- Implement strStr(字符串查找)
- BZOJ4059 [Cerc2012]Non-boring sequences
- 你所不知道的Activity方法
- 微信小程序使用JS隐藏view
- OpenCV图像金字塔:高斯金字塔、拉普拉斯金字塔总结
- hibernate session 的save,get,update,delete 方法
- 使用Charles对Https请求进行抓包
- 关于浏览器 hack 目前ie版本为IE11
- 与网络通信相关的服务和应用进程无法加载和启动、windows通信端口初始化失败