Junior — Middle
What ways in Dart can you check if a string reads the same from left to right and right to left?
sobes.tech AI
Answer from AI
In Dart, you can check if a string is a palindrome (reads the same forwards and backwards) in several ways:
- Compare the string with its reversed copy:
bool isPalindrome(String s) {
String reversed = s.split('').reversed.join('');
return s == reversed;
}
- Use two pointers — one at the start and one at the end, comparing characters alternately:
bool isPalindrome(String s) {
int left = 0;
int right = s.length - 1;
while (left < right) {
if (s[left] != s[right]) return false;
left++;
right--;
}
return true;
}
Both methods are effective for palindrome checking.