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

LeetCode Implement strStr()

时间:2014-10-23 01:16:35      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   sp   div   on   art   

Implement strStr().

Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

 

 1 public class Solution {
 2     public String strStr(String haystack, String needle) {
 3         if (haystack.equals(needle)) {
 4             return haystack;
 5         }        
 6         int haylen=haystack.length();
 7         int neelen=needle.length();
 8         if (neelen>haylen) {
 9             return null;
10         }
11         
12         int i,j=0;
13         int phay=0;
14         while (phay<haylen-neelen) {
15             i=phay;
16             j=0;
17             while (j<neelen && i<haylen && needle.charAt(j)==haystack.charAt(i)) {
18                 ++j;
19                 ++i;
20             }
21             if (j==neelen) {
22                 return haystack.substring(phay);
23             }
24             ++phay;
25             
26         }
27         return null;
28     }
29 }

 

LeetCode Implement strStr()

标签:style   blog   color   io   ar   sp   div   on   art   

原文地址:http://www.cnblogs.com/birdhack/p/4044730.html

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