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的里面的一些写法还是好的~