字符串查找

来源:互联网 发布:淘宝seo教程网盘 编辑:程序博客网 时间:2024/05/16 19:00

TIPS:

1.string=null 和 string=""

String s ;该语句表示只是声明了一个引用变量,但是并没有初始化引用,所以对变量s的任何操作(除了初始化赋值外) 都将引发异常. String s=null; 表示未申请任何内存资源,即些语句表示声明了一个引用变量并初始化引用,但是该引用没有指向任何对象.但可以把它作为参数传递或其它使用,但是不能调用它作为对象的方法String s=""; 表示申请了内存资源,但资源空间值为空。该语句表示声明并引用到一个对象,只不过这个对象为0个字节.所以既然有了对象,就可以调用对象的方法注意:"" 也是字符串
2.判断字符串是否为空
方法一:if(变量.isEmpty())返回true表示,变量中存储的字符串为空,返回false表示变量中存储的的字符串不为空方法二:if(变量.length()==0);判断变量的长度,长度为0表示变量中存储的字符串为空方法三:if(变量.equals(""))使用equals比较值,相同返回true,相异返回false;tips:不推荐用 “变量==null" 来对字符串进行判断。举例: String str=""; 这种情况,虽然str中不存在值,但是也不等于null于是得出结论: ==是用来判断路径是否相同
3.KMP算法学习
对于一个给定的 source 字符串和一个 target 字符串,你应该在 source 字符串中找出 target 字符串出现的第一个位置(从0开始)。如果不存在,则返回 -1
说明

在面试中我是否需要实现KMP算法?

  • 不需要,当这种问题出现在面试中时,面试官很可能只是想要测试一下你的基础应用能力。当然你需要先跟面试官确认清楚要怎么实现这个题。
样例

如果 source = "source" 和 target = "target",返回 -1

如果 source = "abcdabcdefg" 和 target = "bcd",返回 1

class Solution {//此方法为简单的循环方法
    /**
     * Returns a index to the first occurrence of target in source,
     * or -1  if target is not part of source.
     * @param source string to be scanned.
     * @param target string containing the sequence of characters to match.
     */
    public int strStr(String source, String target) {
        //write your code here
        if(source==null || target==null)
          return -1;
        if(target.length()==0)//target==""
          return 0;
        char c  = target.charAt(0);
        for(int i=0;i<source.length()- target.length() + 1;i++){
            if(source.charAt(i)==c){
                String s = source.substring(i,i+target.length());
                if(s.equals(target)){
                   return i;
                }
            }
        }
        return -1;
    }
}

0 0
原创粉丝点击