ITPub博客

首页 > IT职业 > IT职场 > Lintcode13 strStr solution 题解

Lintcode13 strStr solution 题解

IT职场 作者:牛客001 时间:2017-08-01 21:21:10 0 删除 编辑
【题目描述】
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 字符串出现的第一个位置(从0开始)。如果不存在,则返回 -1。
【题目链接】
http://www.lintcode.com/en/problem/strstr/
【题目解析】
对于字符串查找问题,可使用双重for循环解决,效率更高的则为KMP算法。 源码分析 1.边界检查:source和target有可能是空串。 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,容易在循环外再使用时造成编译错误
【答案链接】
http://www.jiuzhang.com/solutions/strstr/

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/31478388/viewspace-2142933/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2017-07-25

  • 博文量
    13
  • 访问量
    3948