Implement strStr()

简介: 实现strStr(),返回下标数字或-1 Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

实现strStr(),返回下标数字或-1

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

 1 package com.rust.TestString;
 2 
 3 public class ImplementstrStr {
 4     public static int strStr(String haystack, String needle) {
 5         int index = 0;
 6         int res = 0;
 7         int len = haystack.length();
 8         int nlen = needle.length();
 9         if (haystack.equals(needle) || nlen == 0) {
10             return 0;
11         }
12         if (len < nlen) {
13             return -1;
14         }
15         if (len == 1 && haystack.equals(needle)) {
16             return 0;
17         } 
18 
19         for (int i = 0; i < haystack.length(); i++) {
20             if (haystack.charAt(i) == needle.charAt(0)) {
21                 if (len - i < nlen) {
22                     return -1;
23                 }
24                 index = i + 1;
25                 res = i;
26                 int j = 1;
27 
28                 while (j < needle.length()){
29                     if (haystack.charAt(index) == needle.charAt(j)) {
30                         index++;
31                         j++;
32                     } else {
33                         break;
34                     }
35                 }
36                 if (index - res == nlen) {
37                     return res;
38                 }
39             }
40         }
41         return -1;
42     }
43 
44     public static void main(String args[]){
45         System.out.println(strStr("abc", "c"));
46         System.out.println(strStr("aadbdffad", "df"));
47         System.out.println(strStr("dbdffad", "df"));
48         System.out.println(strStr("dbdffad", ""));
49     }
50 }

 

目录
相关文章
|
1月前
gets()&puts()函数
gets()&puts()函数。
10 2
|
8月前
|
索引
KMP Implement
KMP Implement
32 0
|
编译器
warning C4995: strcat name was marked as #pragma deprecated
warning C4995: strcat name was marked as #pragma deprecated
60 0
HDOJ/HDU 1075 What Are You Talking About(字符串查找翻译~Map)
HDOJ/HDU 1075 What Are You Talking About(字符串查找翻译~Map)
114 0
|
算法 Java C语言
LeetCode 28:实现strStr() Implement strStr()
公众号:爱写bug(ID:icodebugs) 作者:爱写bug 实现 strStr() 函数。 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。
677 0
1108. Finding Average (20) sscanf() sprintf()
#include #include #include #include #include using namespace std; //sscanf() – 从一个字符串中读进与指定格式相符的数据 //sprintf() – 字符串格式化命令,主要功能是把格式化的数据写入某个字符串中。
907 0