码迷,mamicode.com
首页 > 其他好文 > 详细

Lintcode13 strStr solution 题解

时间:2017-04-25 21:25:32      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:lintcode

【题目描述】

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/


Lintcode13 strStr solution 题解

标签:lintcode

原文地址:http://12799252.blog.51cto.com/12789252/1919309

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!