java中空串_java中空串 “”!=null..字符串要用equals判等

自己写测试用例,区别:字符串为    空串“ ”,空对象null 。

3.2 Implement strStr()

描述

Implement strStr().

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

分析

暴力算法的复杂度是O(m n),代码如下。更高效的的算法有KMP 算法、Boyer-Mooer 算法和

Rabin-Karp 算法。面试中暴力算法足够了,一定要写得没有BUG。

暴力匹配

// LintCode, Implement strStr()

// 暴力解法,时间复杂度O(N*M),空间复杂度O(1)

package leetCode;

public class strstr {

public static int strStrMy(String source, String target) {

if (source == null || target == null) {

return -1;

} else if (target.equals("")) {//target空串""!=null.字符串要用equals判等

return 0;

}

int i = 0, j = 0;

while(i < source.length()) {

if (j < target.length() && source.charAt(i) == target.charAt(j)) {

i++;//相等时,都往后加加。

j++;

} else if (j == target.length()) {

break;//加加到小串结尾时,跳出

} else {//匹配中途有一个不等时,拉回i到(与j相等的下一个)即j-1。

i = i - (j - 1);

j = 0;

}

}

if (j == target.length()) {//判断上面出循环的条件,

return i - target.length();//完全匹配子串

} else {//没找到子串

return -1;

}

}

public static int strStr(String haystack, String needle) {

if (needle.length() == 0)

return 0;

for (int i = 0;; i++) {

for (int j = 0;; j++) {

if (j == needle.length())

return i;

else if (i + j >= haystack.length())

return -1;

else if (needle.charAt(j) != haystack.charAt(i + j))

break;// 不等时,跳出 执行外层循环i++

}

}

}

public static void main(String[] args) {

// String source = "lintcode";

// String target = "lintcode";

//String source = "mississippi";

//String target = "issip";

String source = "";

String target = "a";

// String source = "a";

// String target = "";

// String source = "abcdabcdefg";

// String target = "bcd";

System.out.println("输出结果:" + strStr(source, target));//-1

System.out.println("输出结果--strStrMy" + strStrMy(source, target));//-1

System.out.println("输出结果空串.equals(null) :" + "".equals(null));//flase

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值