每日一題--LeetCode 28(實現strStr())java
阿新 • • 發佈:2018-12-21
題目描述:
程式碼如下(附有解析):
class Solution { public int strStr(String haystack, String needle) { //如果為空直接返回0 if(needle.equals("")){ return 0; } //如果haystack長度小於needle直接返回-1 if(haystack.length()>=needle.length()){ for(int i=0;i<haystack.length();i++){ //判斷第一個字元是否相等 if(haystack.charAt(i)==needle.charAt(0)){ //若從i位置開始haystack往後的長度小於needle直接返回-1 if(haystack.substring(i).length()<needle.length()){ return -1; } //若從i位置開始haystack與needle相等,直接返回i if(haystack.substring(i,needle.length()+i).equals(needle)){ return i; } } } return -1; } return -1; } }