Skip to main content
Back to problems
#647
Medium Algorithms

Palindromic substrings

Two Pointers String Dynamic Programming
72.6% acceptance
Feb 20, 2026
11472
257
Given a string s, return the number of palindromic substrings in it.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn count_substrings(s: String) -> i32 {
    let s = s.as_bytes();
    let n = s.len();
    let mut count = 0;
    for center in 0..2 * n - 1 {
      let mut left = center / 2;
      let mut right = left + center % 2;
      loop {
        if s[left] == s[right] {
          count += 1;
          if left == 0 || right == n - 1 { break; }
          left -= 1;
          right += 1;
        } else {
          break;
        }
      }
    }
    count
  }
}