网站相互推广怎么做,设计公司起名两个字,辽宁网站建设电话,网站开发工具和平台题目描述 实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串#xff0c;在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在#xff0c;则返回 -1。
示例 1:
输入: haystack hello, needle ll
输…题目描述 实现 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() 定义相符。
解法 思路1
/*** 暴力解法直接遍历* 时间复杂度O(m*n)* 空间复杂度O(1)* param haystack* param needle* return*/
public int strStr(String haystack, String needle) {if(.equals(needle)) {return 0;}for(int i0;ihaystack.length();i) {int j0;for(;jneedle.length();j) {if((ij1)haystack.length() || haystack.charAt(i j) ! needle.charAt(j)) {break;}}if(j needle.length()) {return i;}}return -1;}/** * 使用库函数手动cry… * 比思路1快100倍… * 有空需要读懂String.indexOf()方法 * param haystack * param needle * return */ public int strStr(String haystack, String needle) { return haystack.indexOf(needle); }