<script>
function
nextIndex(str,start,c)
{
for
(let i = start; i < str.length; i++) {
if
(str[i] == c)
return
i;
}
return
-1;
}
function
countSubStrings(str)
{
let i, n = str.length;
let countX =
new
Array(n);
let count = 0;
for
(i = n - 1; i >= 0; i--) {
if
(str[i] ==
'x'
)
count++;
countX[i] = count;
}
let nextIndexX = nextIndex(str, 0,
'x'
);
let nextIndexY = nextIndex(str, 0,
'y'
);
count = 0;
while
(nextIndexX != -1 && nextIndexY != -1) {
if
(nextIndexX > nextIndexY) {
nextIndexY = nextIndex(str, nextIndexY + 1, 'y
');
continue;
}
// If '
y
' appears after '
x
'
// every sub-string ending at an '
x
' appearing after this '
y
'
// and starting with the current '
x
' is a valid sub-string
else {
count += countX[nextIndexY];
// Find next occurrence of '
x
'
nextIndexX = nextIndex(str, nextIndexX + 1, '
x');
}
}
return
count;
}
let s =
"xyyxx"
;
document.write(countSubStrings(s));
</script>