[LeetCode]28. 实现 strStr()
实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例 1:
输入: haystack = "hello", needle = "ll"
输出: 2
示例 2:
输入: haystack = "aaaaa", needle = "bba"
输出: -1
说明:
当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-strstr
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
public class Solution {
public int StrStr(string haystack, string needle) {
// 超级偷懒写法
// return haystack.IndexOf(needle);
// 花里胡哨的写法
// if(needle.Length == 0){
// return 0;
// }
// string[] temp = haystack.Split(needle);
// if(temp.Length > 1){
// return temp[0].Length;
// }
// return -1;
// 没啥技术含量的写法
if(needle.Length == 0){
return 0;
};
for(int i = 0; i < haystack.Length; i++){
if(haystack.Length - i < needle.Length){
return -1;
}
int count = 0;
for(int j = 0; j < needle.Length; j++){
if(haystack[i+j] != needle[j]){
break;
}
++count;
//Console.WriteLine($"{haystack[i+j]}:{needle[j]}:Count:{i-count}");
if(count == needle.Length){
return (i+j+1)-count;
}
}
}
return -1;
// 脑袋进水的写法
// if(needle.Length == 0){
// return 0;
// }
// int hayCount = 0;
// int neeCount = 0;
// int count = 0;
// int target = 0;
// while(hayCount < haystack.Length){
// Console.WriteLine(hayCount+":"+neeCount);
// if(haystack[hayCount] == needle[neeCount]){
// hayCount++;
// neeCount++;
// count++;
// }else{
// hayCount++;
// count = 0;
// neeCount = 0;
// target++;
// hayCount = target;
// }
// if(count == needle.Length){
// return hayCount-count;
// }
// }
// return -1;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构