Tuesday, September 8, 2015

[Palindrome][Two Poitner] Valid Palindrome

1. Example

"A man, a plan, a canal: Panama" is a palindrome
"race a car" is not a palindrome

2. Implementation
valid
palindrome
same char
escape special char: continue
l and r
Q1: how to avoid special character?
A1: if there is not  > 'a' or < 'z', we skip the pointer, meaning ++ or --



In Java, the 'int' type is a primitive , whereas the 'Integer' type is an object.

Runtime Error Message:Line 37: java.lang.StringIndexOutOfBoundsException: String index out of range: 2
Last executed input:".,"
//while (!validAphabet(s.charAt(l))) 
 // l++;StringIndexOutOfBoundsException
 //while( !validAlphabet(s.charAt(r))) 
 // r--;
 if ( !isValid(c.charAt(l)) ) 
 { l++; continue; } 
 if ( !isValid(c.charAt(r)) ) 
 { r--; continue; }

//else 
 // NOTE: if return type is required, no need to ELSE
 return false;

// Time:O(string length), Space:O(1)
public boolean isPalindrome(String s)
{
          

  

      // validate the input
      if (s== null || s.length() == 0)
           //return false;
           return true// nothing always palindrome empty to empty.



      int l = 0;
      int r = s.length()-1;
      //for (int i = 0; i < s.length();i++)
      while ( l < r )
      {






           //while (!validAphabet(s.charAt(l)))
             //   l++;
             //while( !validAlphabet(s.charAt(r)))
             //   r--;
             if (  !isValid(c.charAt(l))  )
             {
                  l++;
                  continue;
             }
             if ( !isValid(c.charAt(r))  )
             {
                  r--;
                  continue;
             }







            //if (validAlphbet(s.charAt(l) && validAlphabet(s.charAt(r)) && s.charAt(l) != s.charAt(r)   )
             // NOTE: Uppercase conversion considered
             if (  !isSame(s.charAt(l), s.charAt(r))  )
                 return false;






           l++;               
             r--;




   }



      return true;


     

}
//private boolean validAlphabet(character c)
private boolean validAlphabet(char c)
{

            //if (  (c <= 'Z' || c <= 'z') && (c' >= 'A' || c >= 'a')  ) 
            // NOTE: could be number
            if (  c >= 'a'&& c <='z' || c >='A'&&c<='Z' || c>='0'&&c<='9' )
                     return true;
            //else
            // NOTE: if return type is required, no need to ELSE 
                     return false;  
}

private boolean isSame(char c1, char c2)
{
       if ( c1 >= 'A' && c1 <= 'Z' )
             c1 = (char)( c1- 'A' +'a');
       if ( c2 >= 'A' && c2 <= 'Z') 
             c2 = (char)(c2 - 'A' + 'a');

       return c1== c2;
}
3. Similar Ones
(E) Palindrome Linked List
(H) Shortest Palindrome
(E) Palindrome Number
(M) Palindrome Partitioning

No comments:

Post a Comment