LeetCode_Easy心得:28. Implement strStr()(C语言)
来源:互联网 发布:腾讯域名购买流程 编辑:程序博客网 时间:2024/06/05 05:30
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
/** 题目分析:本题要求我们在输入字符串haystack[] 中找出第一次出现的子字符串needle[] 是位置。 */
Example:
haystack[] = "1234", needle[] = "34";
return 2; // 这里的2是指在字符串haystack[] 中出现子字符串needle[] 的起始位置(也就是haystack[2])
/** 代码思路:首先需要三个整数变量 i, j, temp 来表示字符串下表,其中 i遍历输入字符串haystack[], temp表示 i下标的haystack[], j是遍历子字符串needle[]。具体如下图所示:
最终目标就是比较 haystack[temp]与 needle[j]各位置是否相等,若相等则返回下标 i,即满足条件的下标位置。 */
int strStr(char haystack[], char needle[]) { int i, j, temp; // 三个下标; if(needle[0]=='\0') return 0; // 如果子字符串为空,直接返回0; for(i=0; haystack[i]; i++){ // 用 i遍历haystack[]; temp = i; // 将 i赋值给临时变量 temp; j = 0; // j=0, 表示了子字符串从头遍历; while(needle[j] == haystack[temp] || needle[j] == '\0'){ // needle[j]与 haystack[temp]比较; if(needle[j] == '\0') return i; // needle[j] == '\0'说明子字符串比较完成,返回此事下标 i; else j++, temp++;// 即needle[j]还没有全部比完,下表继续向后推; } } return -1; // 不存在即 needle[]子字符串,因此返回-1;}// LeetCode运行时间:630ms ± 10ms;
阅读全文
0 0
- LeetCode_Easy心得:28. Implement strStr()(C语言)
- LeetCode_Easy心得:1. Two Sum(C语言)
- LeetCode_Easy心得:7. Reverse Integer(C语言)
- LeetCode_Easy心得:9. Palindrome Number (C语言)
- LeetCode_Easy心得:13. Roman to Integer (C语言)
- LeetCode_Easy心得:14. Longest Common Prefix(C语言)
- LeetCode_Easy心得:20. Valid Parentheses(C语言)
- LeetCode_Easy心得:21. Merge Two Sorted Lists(C语言)
- LeetCode_Easy心得:27. Remove Element(C语言)
- LeetCode_Easy心得:35. Search Insert Position(C语言)
- Leetcode c语言-Implement strStr()
- LeetCode_Easy心得:26. Remove Duplicates from Sorted Array(C语言)
- 【C++】【LeetCode】28. Implement strStr()
- [leetcode-28]implement strstr()(C语言)
- 【leetcode】28. Implement strStr()(Python & C++)(KMP算法)
- 28. Implement strStr()(重要!)
- 28. Implement strStr()(64.79%)
- 【LeetCode算法练习(C++)】Implement strStr()
- FFMpeg无损合并视频的多种方法
- 纹理特征简介
- eclipse转idea后的体会
- Java基础:switch case default 语句的的使用
- 润乾报表v5一直停滞在取数完成正在计算的分析
- LeetCode_Easy心得:28. Implement strStr()(C语言)
- React学习资源汇总
- js 的一些简单方法
- 安卓-橡皮擦擦线完整实现
- 技术文章|如何更好地使用容器技术实现不可变基础设施
- Visual Studio2013常用快捷键
- java积累----Calendar----获取上月的起始时间和上月结束时间
- 数学建模:MATLAB R2016b下载与安装教程
- iOS经典讲解之百度地图的使用及案例(iOS地图SDK)