这几天在学如何搭虚拟机。。用Hadoop,还有重新补了一下java的知识
就做了几题相对简单的题目,leetcode也是easy的题目
28. Implement strStr()
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
这个题目要求很简单,当然题目里面还说用indexOf,我认为完全没必要,java可以整个子串去比较何必一个一个字符比较呢?
值得注意的是我日常忘记空字符串的情况,每次第一次提交都GG。。。
下次真的要注意了
代码如下:
class Solution {
public int strStr(String haystack, String needle) {
if(needle.equals("") && haystack.equals(""))
return 0;
int counter = 0;
for(int i = 0;i < haystack.length() - needle.length() + 1;i++){
if(haystack.substring(i,i + needle.length()).equals(needle))
return i;
}
return -1;
}
}
非常的简短,一开始先把空字符串的情况处理了,然后直接用java的substring以及equals方法去比较就搞定了
毕竟在java里面,字符串对象都是一创建就固定的,然后=运算符之类的只是改变了引用的地址而已,所以比较字符串内容尽量用equals方法不要用==,==可能会出错。
本文介绍了一个简单的Java实现strStr()方法的例子,该方法用于查找一个字符串在另一个字符串中首次出现的位置。通过使用substring和equals方法进行子串比较,避免了逐字符比较的繁琐。

4430

被折叠的 条评论
为什么被折叠?



