admin管理员组

文章数量:1636897

题目链接:https://leetcode/problems/implement-strstr/

题目:implement strStr().

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

解题思路:题意为在字符串变量haystack找出第一次出现字符串needle的索引值,若不存在就返回-1。本意应该是让答题者自己写函数实现的,试了一下函数indexOf(),也是可以Accept的。嗯,就是这样。

示例代码:

public class Solution 
{
	 public int strStr(String haystack, String needle)
	 {
		 return haystack.indexOf(needle);
	 }
}

方法二:

public class Solution 
{
	 public int strStr(String haystack, String needle)
	 {
		 if(haystack.length()<needle.length())
			 return -1;
		 if("".equals(needle)&&"".equals(haystack))
			 return 0;
		 if("".equals(needle))
			 return 0;
		 int j=0;  //needle索引
		 int i=0;  //haystack索引 
		 int k=0; //记录上一次相等的索引值
		 while((k+needle.length())<=haystack.length()) 
		 {
			 if(haystack.charAt(i)==needle.charAt(j))
			 {
				 i++;
				 j++;
				 if(j==needle.length())
				 {
					 return k;
				 }
			 }
			 else
			 {
				 j=0;	
				 k++;
				 i=k;
			 }
		 }
		return -1;
	 }
}


本文标签: OJLeetCodestrStrimplement