码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode -- Day 17

时间:2015-07-25 00:01:03      阅读:369      评论:0      收藏:0      [点我收藏+]

标签:

substring

Question 1

Implement strStr()

Implement strStr().

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

Below is my first direct solution, which looks complex in different case checking using if, else. 

 

 1 public int strStr(String haystack, String needle) {
 2         if (haystack == null || needle == null)
 3             return -1;
 4             
 5         int len1 = haystack.length();
 6         int len2 = needle.length();
 7         
 8         if (len2==0)
 9             return 0;
10             
11         if (len1 <= len2){
12             if (haystack.equals(needle)) return 0;
13             else return -1;
14         }
15             
16         for (int i = 0; i < len1; i ++){
17             if (haystack.charAt(i) == needle.charAt(0)){
18                 if (i+len2 > len1)
19                     return -1;
20                 String temp = haystack.substring(i, i+len2);
21                 if (needle.equals(temp))
22                     return i;
23             }
24         }
25         return -1;
26     }

 

 

 

Leetcode -- Day 17

标签:

原文地址:http://www.cnblogs.com/timoBlog/p/4674957.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!