【題目描述】
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/