Implement strStr() Leetcode

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

 

真是要崩溃了。。。这道题好像是第三遍做了还是做不利索。。。= =
 
public class Solution {
    public int strStr(String haystack, String needle) {
        if (haystack == null || haystack.length() == 0) {
            return needle == null || needle.length() == 0 ? 0 : -1;
        }
        if (needle == null || needle.length() == 0) {
            return 0;
        }
        for (int i = 0; i < haystack.length(); i++) {
            for (int j = 0; j < needle.length(); j++) {
                if (i + j >= haystack.length()) {
                    return -1;
                }
                if (haystack.charAt(i + j) != needle.charAt(j)) {
                    break;
                }
                if (j == needle.length() - 1) {
                    return i;
                }
            }
        }
        return -1;
    }
}

需要注意的有以下几点:

1. i + j >= haystack.length()的时候直接return -1,没有必要看后面的了。因为这个时候第二个已经比第一个可以比较的子串长度长了。

2. 不是单层循环就可以的,因为每个值都可能是开始的值。

3. j == needle.length() - 1要放在判断下面,因为如果第二个字符串长度为一,就直接返回0了。

 

C++写法:

class Solution {
public:
    string reverseVowels(string s) {
        int i = 0, j = s.size() - 1;
        while (i < j) {
            i = s.find_first_of("aeiouAEIOU", i);
            j = s.find_last_of("aeiouAEIOU", j);
            if (i < j) {
                swap(s[i++], s[j--]);
            }
        }
        return s;
    }
};

find_first_of和find_last_of还挺好用的。

posted @ 2017-06-16 02:24  璨璨要好好学习  阅读(311)  评论(0编辑  收藏  举报