首页 > 其他 > 详细

Leetcode -- Day 17

时间:2015-07-24 23:57:51      阅读:261      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!