zoukankan      html  css  js  c++  java
  • 找子串

    strstr (a.k.a find sub string), is a useful function in string operation.
    You task is to implement this function.
    
    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 is not exist in source, just return -1.
    
    Example
    If source="source" and target="target", return -1.
    
    If source="abcdabcdefg" and target="bcd", return 1.
    
    Challenge
    O(n) time.
    
    Clarification
    Do I need to implement KMP Algorithm in an interview?
    
        - Not necessary. When this problem occurs in an interview,
        the interviewer just want to test your basic implementation ability.
    

      

    JAVA

    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) {
            if (source == null || target == null) {
                return -1;
            }
    
            int i, j;
            for (i = 0; i < source.length() - target.length() + 1; i++) {
                for (j = 0; j < target.length(); j++) {
                    if (source.charAt(i + j) != target.charAt(j)) {
                        break;
                    } //if
                } //for j
                if (j == target.length()) {
                    return i;
                }
            } //for i
    
            // did not find the target
            return -1;
        }
    }

    源码分析

    1. 边界检查:sourcetarget有可能是空串。
    2. 边界检查之下标溢出:注意变量i的循环判断条件,如果是单纯的i < source.length()则在后面的source.charAt(i + j)时有可能溢出。
    3. 代码风格:(1)运算符==两边应加空格;(2)变量名不要起s1``s2这类,要有意义,如target``source;(3)即使if语句中只有一句话也要加大括号,即{return -1;};(4)Java 代码的大括号一般在同一行右边,C++ 代码的大括号一般另起一行;(5)int i, j;声明前有一行空格,是好的代码风格。
    4. 不要在for的条件中声明i,j,容易在循环外再使用时造成编译错误
  • 相关阅读:
    jQuery 基本选择器
    JavaScriptif while for switch流程控制 JS函数 内置对象
    JavaScrip基本语法
    数据库 存储引擎 表的操作 数值类型 时间类型 字符串类型 枚举集合 约束
    数据库基础知识 管理员 用户登录授权的操作
    粘包的产生原理 以及如何解决粘包问题
    socket TCP DPT 网络编程
    2018年年终总结
    Android技术分享
    No accelerator found
  • 原文地址:https://www.cnblogs.com/lyc94620/p/9914501.html
Copyright © 2011-2022 走看看