Tuesday, May 28, 2013

Palindrome Integer @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
Determine whether an integer is a palindrome. Do this without extra space.
Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.
When we get a question, we need to think through the special cases that may have. I think we could ask the interviewer for some vague cases. For example, in this problem, we can either define -12321 be palindrome or not. My code is designed for not. In the first place, I wanna use Dynamic Programming to solve this. To recursive down the integer, and compare the two integers beside. While, my first version of DP code went through in my compiler, while not in Online Judge. Because DP is too slow which causes time limit exceed. And as we all know that, all the DP can be transferred into loop. We only need to think problem from bottom up to top down. My code paste below. Pay attention to some barrier condition which is quite easy cause infinite loop. 



4 comments:

  1. should add following code into your while loop to include 10101 case:

    if((x/10)%10 == 0)
    {
    if((x/power)*10 != x/(power/10))
    return false;
    else
    {
    x = x = (x - (x/power)*power - x%10) / 100;
    power /= 10000;
    }

    }

    ReplyDelete
    Replies
    1. I don't think so. In 10101 case, the power will be 10000 before go into the while loop. Since the frond 1 equals the back 1, so after the first loop, the variable x become 10 and power become 100. Do the loop again and you will find it still goes through. After the second loop, the variable x become 1 and the power become 1. Then do a final loop and it returns true at the end.

      Delete
  2. Why you use power? Isn't that a extra variable you use? But the question says do not use extra space.

    ReplyDelete
    Replies
    1. 我已经好久木有刷题了。extra space在面试的理解应该是O(n)的space,constant的space是可以的。

      Delete

Leetcode 316. Remove Duplicate Letters

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