LeetCode-28 Implement strStr() (找出字串位置)

LeetCode-28 Implement strStr() (找出字串位置)

Implement strStr().

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

Update (2014-11-02):
The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char * or String, please click the reload button  to reset your code definition.

 

 

 

public class Solution {
    public int strStr(String haystack, String needle) {
        if(needle.length() == 0)
            return 0;
        int j = 1;
    	for (int i = 0; i < haystack.length()-needle.length()+1; i++) {
			if (haystack.charAt(i) == needle.charAt(0)) {//(= =)
				for (j=1; j < needle.length(); j++) {
					if (haystack.charAt(i+j) != needle.charAt(j)) {
						break;
					}
				}
				if (j == needle.length()) {
					return i;
				}else {
					j = 1;
				}
			}
		}
    	return -1;
    }
}

Runtime: 272 ms

在(= =)的位置尝试用substring直接整个判断,

然后速度貌似并没有更快。。

顺带一提,substring底层是按需要new一个新的字符串。
如下:

    public String substring(int beginIndex, int endIndex) {
        if (beginIndex < 0) {
            throw new StringIndexOutOfBoundsException(beginIndex);
        }
        if (endIndex > value.length) {
            throw new StringIndexOutOfBoundsException(endIndex);
        }
        int subLen = endIndex - beginIndex;
        if (subLen < 0) {
            throw new StringIndexOutOfBoundsException(subLen);
        }
        return ((beginIndex == 0) && (endIndex == value.length)) ? this
                : new String(value, beginIndex, subLen);
    }


这里的new String方法

    public String(char value[], int offset, int count) {
        if (offset < 0) {
            throw new StringIndexOutOfBoundsException(offset);
        }
        if (count < 0) {
            throw new StringIndexOutOfBoundsException(count);
        }
        // Note: offset or count might be near -1>>>1.
        if (offset > value.length - count) {
            throw new StringIndexOutOfBoundsException(offset + count);
        }
        this.value = Arrays.copyOfRange(value, offset, offset+count);
    }

...以,发现继续往下。。Arrays.copyOfRange里面又用到System.arraycopy.,,,然后底层native的方法就看不到了难过

但大致知道substring的里面的一些写法还是好的~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值