13. strstr

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/frankly01/article/details/79297403

  Problem: For a given source string and a target string, you should output the first index(from 0) of target string in source string.
If target does not exist in source, just return -1.

  翻译:对给定的source和target两个字符串,在source中查找出完全匹配的target字符串的第一个所在的字符位置。如target不存在于source中则输出-1。

   例子:
source: “source”
target:  “target”
return:   -1

source: “abcabcda”
target:  “bcd”
return:    4


  第一反应是利用循环进行逐一比较,如能完全匹对完target字符串内容,则找到当前开始的第一个字符在所在位置,如不能则从下一个位置继续进行配对,这种思路相对简单,很容易思考。

  • 需考虑字符串null情况
  • 需考虑字符串为空情况
  • 需考虑字符串首尾情况

public class Solution {
    /*
     * @param source: source string to be scanned.
     * @param target: target string containing the sequence of characters to match
     * @return: a index to the first occurrence of target in source, or -1  if target is not part of source.
     */
    public int strStr(String source, String target) {
        // write your code here
        if (source==null || target ==null)//判断字符串null
        return -1;
        for (int i = 0 ;  i < source.length()-target.length()+1 ; i++ ){//判定条件i排除字符串首尾及为空的极端情况
            int j=0;
            for(j = 0 ; j<target.length();j++){
                if(source.charAt(i+j)!=target.charAt(j)){
                    break;
                }
            }
            if (j==target.length())
            return i; 
        }
        return -1;
    }
}


  双循环情况,方法的运算量相对较高,故而改进出去第二个循环体,用string的substring进行字符串的匹对。

public class Solution {
    /*
     * @param source: source string to be scanned.
     * @param target: target string containing the sequence of characters to match
     * @return: a index to the first occurrence of target in source, or -1  if target is not part of source.
     */
    public int strStr(String source, String target) {
        // write your code here
        if (source==null || target ==null)//判断字符串null
        return -1;
            for (int i = 0 ;  i < source.length()-target.length()+1 ; i++ ){  //判定条件i排除字符串首尾及为空的极端情况         
            if( source.substring(i,i+target.length()).equals( target.substring(0,target.length()))){  // 利用字符串自带方法substring,并需注意equals的使用
                return i;
            }           
            }
        return -1;
    }
}

  联想相关算法,如使用KMP算法,改进的字符串匹配算法,应是较为简便的解题思路。
算法代码后续补。

猜你喜欢

转载自blog.csdn.net/frankly01/article/details/79297403