forked from iiitv/algos
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Browse files
Browse the repository at this point in the history
* Added Longest Palindromic Substring [Go] * Adjust code style and add entry to README
- Loading branch information
1 parent
3818698
commit edc5b47
Showing
2 changed files
with
47 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
46 changes: 46 additions & 0 deletions
46
longest_palindromic_substring/longest_palindromic_substring.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
package main | ||
|
||
import "fmt" | ||
|
||
// expandAroundCenter returns length of palindromic substring | ||
func expandAroundCenter(runes []rune, left int, right int) int { | ||
n := len(runes) | ||
|
||
for left >= 0 && right < n && runes[left] == runes[right] { | ||
left-- | ||
right++ | ||
} | ||
return right - left - 1 | ||
} | ||
|
||
// LongestPalindromicSubstring returns the longest palindromic substring in | ||
// provided string. | ||
// Time complexity: O(n^2) | ||
// Space complexity: O(1) | ||
func LongestPalindromicSubstring(str string) string { | ||
start, end := 0, 0 | ||
runes := []rune(str) | ||
|
||
for i := 0; i < len(runes); i++ { | ||
a := expandAroundCenter(runes, i, i) | ||
b := expandAroundCenter(runes, i, i+1) | ||
|
||
length := 0 | ||
if a > b { | ||
length = a | ||
} else { | ||
length = b | ||
} | ||
|
||
if length > end-start { | ||
start = i - (length-1)/2 | ||
end = i + length/2 | ||
} | ||
} | ||
return string(runes[start : end+1]) | ||
} | ||
|
||
func main() { | ||
str := "And the longest palindrome is... neveroddoreven!" | ||
fmt.Println(LongestPalindromicSubstring(str)) | ||
} |