Advertisement
rajeshinternshala

Untitled

Aug 12th, 2023
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.74 KB | None | 0 0
  1.  static int count;
  2.  
  3.     public int countSubstrings(String str) {
  4.  
  5.         count = 0;
  6.         for (int i = 0; i < str.length(); i++) {
  7.             /**
  8.              * Expand for the odd length palindrome string
  9.              */
  10.             expandPalindrome(str, i, i);
  11.             /**
  12.              * Expand for the even length palindrome string
  13.              */
  14.             expandPalindrome(str, i, i + 1);
  15.  
  16.         }
  17.         return count;
  18.     }
  19.  
  20.     private void expandPalindrome(String str, int i, int j) {
  21.         while (i >= 0 && j < str.length()) {
  22.             if (str.charAt(i) == str.charAt(j)) {
  23.                 count++;
  24.             } else {
  25.                 break;
  26.             }
  27.             i--;
  28.             j++;
  29.         }
  30.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement