zoukankan      html  css  js  c++  java
  • lintcode13- strStr- easy

    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.

    Example

    If source = "source" and target = "target", return -1.

    If source = "abcdabcdefg" and target = "bcd", return 1.

    二重循环,判断一下交错时的下标特点,提早排除。

    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){
                return -1;
            }
    
            for (int sPnt = 0; sPnt < source.length() - target.length() + 1; ++sPnt){
                int tPnt = 0;
                for (tPnt = 0; tPnt < target.length(); ++tPnt){
                    if (sPnt + tPnt >= source.length()){
                        return -1;
                    }
                    else if (source.charAt(sPnt + tPnt) != target.charAt(tPnt)){
                        break;
                    }
                }
                if (tPnt == target.length()){
                    return sPnt;
                }
            }
    
            return -1;
    
        }
    }

    1. 避免不必要的对比:写for (int sPnt = 0; sPnt < source.length() - target.length() + 1; ++sPnt){

    2.如果你for循环的循环变量之后还要用,就在外面定义它,然后在for循环里给它赋值!!这样for结束后还能用。

    int tPnt = 0;
    for (tPnt = 0; tPnt < target.length(); ++tPnt){

    3.考虑输入““””问题,字符串问题里“” 和null还是不一样的。

    4.“”的length()为0

    5.“”不能做charAt(0)操作。

  • 相关阅读:
    hdu 1042 N!
    hdu 1002 A + B Problem II
    c++大数模板
    hdu 1004 Let the Balloon Rise
    hdu 4027 Can you answer these queries?
    poj 2823 Sliding Window
    hdu 3074 Multiply game
    hdu 1394 Minimum Inversion Number
    hdu 5199 Gunner
    九度oj 1521 二叉树的镜像
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7560846.html
Copyright © 2011-2022 走看看