简历:The Google Resume: How to Prepare for a Career and Land a Job at Apple, Microsoft, Google, or any Top Tech Company
算法学习书籍:Introduction to Algorithms
编程珠玑:Programming Pearls (2nd Edition)
C++ 学习:The C++ Programming Language, 4th Edition
经典操作系统书籍,龙书:Operating System Concepts
创业:The Start-up of You: Adapt to the Future, Invest in Yourself, and Transform Your Career
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
The idea is normal. Compare the first char of needle with each char of haystack. If found a char equal, then look into it.
My code went through most of the case, while the last one failed. After learning from others' code, I added a judge line to avoid unnecessary comparing.
While, when I was writing the code, I have some problems. The parameters are represented by char* haystack and char* needle. When I was trying to see whether the needle is empty or not, I wrote if(needle==NULL) return haystack; which failed. While, I used if(!*needle) return haystack; which worked out. So what's the difference between ''' and NULL when it comes to a string. Can anybody viewing my blog answer that for me?
关键点:char *s1表示的string是指向数组的指针,和string s2这样的container不一样。对于char *s我们用strlen(s)来求长度,而string用s2.size()来求。对于s1就用指针操作。
对于避免多余的判断,我们用一个条件,假如判断完一次needle and haystack,剩余的haystack的长度小于needle了,我们就直接return。
I think I can answer your question.
ReplyDeleteIf char *needle == NULL. It means needle is a null pointer, and its value (i.e., the address it points to) is 0x0000. However, if char *needle == "", the value of needle is not 0x0000, instead the value is the starting address of an empty string "".
*needle==NULL, means *needle=='\0', where the char* points to the end of a c style string;
Deleteneedle==NULL, means pointer of needle points to an empty address