【LeetCode OJ 28】Implement strStr()

1170 ワード

タイトルリンク:https://leetcode.com/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);
	 }
}

方法2:
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;
	 }
}