We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Special String Again
- Discussions
Special String Again
Special String Again
+ 0 comments JS version all pass
function substrCount(n, s) { let count = 0, strArr = s.split("") for (let i = 0; i < n; i++) { count++ let goLeft = i - 1, goRight = i + 1, value = strArr[i + 1] while (goLeft >= 0 && goRight < n) { if (strArr[goLeft--] == value && strArr[goRight++] == value) count++ else break } goLeft = i, goRight = i + 1 while (goLeft >= 0 && goRight < n) { if (strArr[goLeft--] == value && strArr[goRight++] == value) count++ else break } } return count }
+ 1 comment easy understand java code with O(n^2) time complexity please refer to leetcode647:palindromic substrings for this templates.
public class Solution { static int count; // Complete the substrCount function below. static long substrCount(int n, String s) { count = 0; //O(n^2) for(int i = 0 ; i < n;i++){//O(n) helperOdd(i,i,s);//0(n) helperEven(i,i+1,s);//O(n) } return count; } static void helperEven(int i, int j, String s){ if(i >=0 && j < s.length()){ char c = s.charAt(i); while(i >=0 && j < s.length() && s.charAt(i) == s.charAt(j)&& s.charAt(i) == c){ count++; i--; j++; } } } static void helperOdd(int i, int j, String s){ count++; i--; j++; helperEven(i,j,s); }
+ 2 comments Java
static long substrCount(int n, String s) { long count = n; char[] arr = s.toCharArray(); for (int i = 0; i < n - 1; i++) { for (int k = i + 1; k < n; k++) { if (arr[i] == arr[k]) count++; if (arr[i] != arr[k]) { int lastIndex = k * 2 - i; if (lastIndex < n && s.substring(i, k).equals(s.substring(k + 1, lastIndex + 1))) { count++; } break; } } } return count; }
+ 0 comments C++ Simple solution
long substrCount(int n, string s) { long ans = 0; char c = s[0]; int j=0; while(j<s.length()) { char c= s[j]; long cnt = 1; j++; while(j<s.length() && s[j]==c)j++, cnt++; ans = ans + (cnt+1)*cnt/2; } for(int i=1;i<n-1;++i){ if(s[i]==s[i-1]||s[i]==s[i+1])continue; int x = i-1; int y = i+1; char z = s[i-1]; while(x>=0&&y<n&&s[x]==s[y]&&s[x]==z)x--,y++; ans = ans + (i-x-1); } return ans; }
+ 1 comment hopefully a readable one:
long substrCount(int n, string s) {
// minimum count is n int count = n; for (int i=0;i<n;i++) { char current = s[i]; // just continuous - equal substrings like "aaa" int j = i+1; while (j<n && s[j] == current) { count++; j++; } // continuous on left and right side from current char j = 1; while (i-j>=0 && i+j<n && // array bounds current != s[i+j] && // next is different than current s[i-j] == s[i+j] && // char's on left and right sides are the same s[i+j] == s[i+1] // next char must be the same as previous ) { count++; j++; } } return count;
}
Load more conversations
Sort 769 Discussions, By:
Please Login in order to post a comment