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

Implement strStr()

时间:2014-10-02 10:38:22      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   java   for   strong   sp   

Implement strStr().

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

答案

public class Solution {
    public String strStr(String haystack, String needle) {
        if(needle==null||haystack==null)
        {
            return null;
        }
        Map<Character,Integer> map=new HashMap<Character,Integer>();
        int i;
        int j;
        for(i=0;i<needle.length();i++)
        {
            map.put(needle.charAt(i),i);
        }
        for(i=0;i<=haystack.length()-needle.length();)
        {
            for(j=0;j<needle.length();j++)
            {
                if(haystack.charAt(i+j)!=needle.charAt(j))
                {
                    break;
                }
            }
            if(j==needle.length())
            {
                break;
            }
            if(i+j+1>=haystack.length()||!map.containsKey(haystack.charAt(i+j+1)))
            {
                i=i+j+2;
            }
            else
            {
                i=Math.max(i+1,i+j+1-map.get(haystack.charAt(i+j+1)));
            }
        }
        if(i>haystack.length()-needle.length())
        {
            return null;
        }
        return haystack.substring(i);
    }
}

Implement strStr()

标签:style   blog   color   io   ar   java   for   strong   sp   

原文地址:http://blog.csdn.net/jiewuyou/article/details/39735177

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