Lintcode13 strStr solution 题解

【题目描述】

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/


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章