Monday, June 10, 2013

Implement strStr()@leetcode

刷题必备书籍Cracking the Coding Interview: 150 Programming Questions and Solutions 

简历: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。

2 comments:

  1. I think I can answer your question.
    If 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 "".

    ReplyDelete
    Replies
    1. *needle==NULL, means *needle=='\0', where the char* points to the end of a c style string;
      needle==NULL, means pointer of needle points to an empty address

      Delete

Leetcode 316. Remove Duplicate Letters

 这道题表面问的是如何删除重复,实际在问如何从多个字符选取一个保留,从而让整个字符串按升序排列。那么策略就是对于高顺位的字符比如‘a',就要选靠前位置的保留,而低顺位字符如’z'则应该尽量选取靠后位置保留。 算法大概思路:每看到一个字符,我们要决定是否保留 1. ...