It is not easy to write an algorithm question without a bug.
It is necessary to consider whether each variable is applicable in your algorithm. What are the prerequisites for your algorithm?
This and parameter check are another thing. The parameter check is said to be a necessary process. In fact, this is related to the specific implementation.
If the specific implementation of irrelevant parameters, you do not need to do any parameter checks
For example, you often need to check whether the input parameter is null. If the function wants to obtain the value of this address, you must check whether the pointer is null, which is irrelevant to the parameter check.
For example
Implement strstr ()
Implement strstr ().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
This is a question in leetcode. Let's write the most violent method, but it is not very careful to implement bug-free.
My first code is
public String strStr(String haystack, String needle) { for (int i = 0; i < haystack.length(); i++) {for(int j = 0;j<needle.length();j++){if(haystack.charAt(i+j) == needle.charAt(j)){if(j == needle.length() -1)return haystack.substring(i);elsecontinue;}else{break;}}}return null; }
This error is not comprehensive. In fact, when writing I + J, you should consider whether I + J is out of bounds.
View my second code
public String strStr(String haystack, String needle) { if(haystack == null || haystack.length() == 0){return null;}if(needle == null || needle.length() == 0){return haystack;}for (int i = 0; i < haystack.length(); i++) {for(int j = 0;j<needle.length();j++){if(i + j >= haystack.length()) return null;if(haystack.charAt(i+j) == needle.charAt(j)){if(j == needle.length() -1)return haystack.substring(i);elsecontinue;}else{break;}}}return null;}
This time it was almost correct, but it still did not pass. After adjusting the positions of the first two sentences, it was over. The final code is as follows.
public String strStr(String haystack, String needle) { if(needle == null || needle.length() == 0){return haystack;} if(haystack == null || haystack.length() == 0){return null;}for (int i = 0; i < haystack.length(); i++) {for(int j = 0;j<needle.length();j++){if(i + j >= haystack.length()) return null;if(haystack.charAt(i+j) == needle.charAt(j)){if(j == needle.length() -1)return haystack.substring(i);elsecontinue;}else{break;}}}return null; }
Through this example, I feel that I have to worry about writing code and take into account the applicable conditions of the variables. I have to think about the relationship between the variables.
Write bug-free code