您的位置:首页 > 其它

LeetCode:strStr 暴力美学

2013-12-30 19:10 267 查看
题目:

Implement strStr().

Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
思路:暴力解决:
public String strStr(String haystack, String needle) {
if (needle == null || haystack == null)
return null;
if (haystack.length() == 0 && needle.length() == 0)
return haystack;
if (needle.length() == 0)
return haystack;
for (int i = 0; i < haystack.length() - needle.length()+1; i++) {
if (haystack.charAt(i) == needle.charAt(0)) {
int x = i + 1;
int j = 1;
boolean flag = true;
while (x < haystack.length() && j < needle.length()) {
if (haystack.charAt(x) == needle.charAt(j)) {
x++;
j++;
} else {
flag = false;
break;
}
}
if (flag)
return haystack.substring(i);
}
}
return null;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: