Given a string, your task is to count how many palindromic substrings in this string.
The substrings with different start indexes or end indexes are counted as different substrings even they consist of the same characters.
The substrings with different start indexes or end indexes are counted as different substrings even they consist of the same characters.
Example 1:
Input: "abc"
Output: 3
Approach
Java
public class PalindromicSubstrings {public static void main(String[] args) {String str = "abc";System.out.println(countSubstrings(str));}// function to check if// string is palindrome or notstatic boolean ispalindrome(String s) {int n = s.length();int flag = 0;for (int i = 0; i < n / 2; i++) {if (s.charAt(i) != s.charAt(n - i - 1)) {flag = 1;break;}}if (flag == 0)return true;return false;}static int countSubstrings(String s) {int cnt = 0;for (int i = 0; i < s.length(); i++) {String str = "";for (int j = i; j < s.length(); j++) {str += s.charAt(j);if (ispalindrome(str))cnt++;}}return cnt;}}
C++
#include <bits/stdc++.h>using namespace std;//function to check if//string is palindrome or notbool ispalindrome(string &s){int n=s.size();int flag=0;for(int i=0;i<n/2;i++){if(s[i]!=s[n-i-1]){flag=1;break;}}if(flag==0)return true;return false;}int countSubstrings(string s){int cnt=0;for(int i=0;i<s.size();i++){string str="";for(int j=i;j<s.size();j++){str+=s[j];if(ispalindrome(str))cnt++;}}return cnt;}int main(){string str="abc";cout<<countSubstrings(str);return 0;}
No comments:
Post a Comment