longest-palindromic-substring.dart (1886B)
1 //Longest palindromic substring solution using dart. 2 //Find the longest palindrome contained in a string and return it. 3 //The solution I used to this problem was to place all indexes of characters into a map. 4 //I then iterated through the string again and each repeat value is checked to see if it creates a palindrome. 5 class Solution { 6 String longestPalindrome(String s) { 7 String longest = ""; 8 Map <String, List<int>> characters = {}; 9 for(int i = 0 ; i < s.length ; ++i){ 10 if(characters[s[i]] != null){ 11 characters[s[i]]?.add(i); 12 } 13 else{ 14 characters[s[i]] = [i]; 15 } 16 } 17 for(int i = 0 ; i < s.length ; ++i){ 18 if((characters[s[i]]?.length ?? 0) >= 2){ 19 List<int> indexes = characters[s[i]] ?? []; 20 for(int x = 0 ; x < indexes.length ; ++x){ 21 for(int z = indexes.length - 1; z > x ; --z){ 22 if((indexes[z] - indexes[x]).abs() >= longest.length){ 23 String sub = s.substring(indexes[x] , indexes[z] + 1); 24 if(isPalindrome(sub)){ 25 longest = sub; 26 } 27 } 28 } 29 } 30 } 31 } 32 if(longest == "" && s.length > 0){ 33 return s[0]; 34 } 35 return longest; 36 } 37 bool isPalindrome(String check){ 38 if(check.length == 1){ 39 return true; 40 } 41 if(check.length == 2){ 42 if(check[0] == check[1]){ 43 return true; 44 } 45 return false; 46 } 47 for(int i = 0 ; i < check.length / 2 + 1 ; ++i){ 48 if(check[i] != check[check.length - 1 - i]){ 49 return false; 50 } 51 } 52 return true; 53 } 54 }