algorithms

Algorithm implementations
git clone git://git.laack.co/algorithms.git
Log | Files | Refs | README

palindromic-substrings.cpp (859B)


      1 class Solution {
      2 public:
      3     int countSubstrings(string s) {
      4         
      5         // idea:
      6         // move out from each index, incrementing as we find
      7         // more valid palindromes
      8         // wctc = O(n^2)
      9 
     10         int count = 0;
     11 
     12         for(int i = 0; i < s.length(); ++i) {
     13             // have to add this to handle cases where
     14             for(int offset = 0; offset <= 1; ++offset) {
     15                 int left = i; 
     16                 int right = i + offset;
     17                 while(left >= 0 && right < s.length()) {
     18                     if (s[left] == s[right]) {
     19                         count += 1;
     20                         left -= 1;
     21                         right += 1;
     22                     }
     23                     else {
     24                         break;
     25                     }
     26                 }
     27             }
     28           
     29 
     30         }
     31 
     32         return count;
     33     }
     34 };