' Note that integer division results in a truncated value, e.g. ' Only need to iterate until half of the string length. If value.Length = 0 Then Return False ' or True, depends on your preference ' Shortcut case if the input string is empty. Value = value.Replace(" ", "") // Note String.Replace(String,String) runs in O(n) time and if replacement is necessary then O(n) space. If value Is Nothing Then Throw New ArgumentNullException("value") In VB.NET: Public Shared Function IsPalindrome(value As String) As Boolean The optimal algorithm for checking a palindrome needs only iterate through half of the input string - by comparing value with value for n = 0 to length/2. However consider the essential properties of a palindrome: the first half of a string is equal to the second half of the string in reverse. NET) (plus extra iterations for your Trim and Replace calls). While using string reversal works, it is suboptimal because you're iterating over the string at least 2 full times (as string reversal creates a copy of a string because strings are immutable in.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |