My code works in console but gives the wrong result in hackerank Problem: Print count of all substrings that are palindromes from a string
function isPalindrome(str) { var len = str.length; var mid = Math.floor(len / 2); for (var i = 0; i < mid; i++) { if (str[i] !== str[len - 1 - i]) { return false; } } //Had to use this lengthy function because in //str == str.split('').reverse().join(''); //I was getting error that split is not a function return true; } function scatterPalindrome(str) { var result = [], c = 0; for (let i = 0; i < str.length; i++) { for (let j = i + 1; j < str.length + 1; j++) { result.push(str.slice(i, j)); } } for (let i = 0; i < result.length; i++) { let k = result[i]; if (isPalindrome(k)) c++; } return c; // the answer was always 1 } console.log(scatterPalindrome("abc"));
input: "abc"
expected output: 3
actual output:1
As I can't comment, so answering here, I will say you should check if they have mentioned there are many test cases, and in each test case you have to do the query then this is reasonable that your output and their output will not match
take no.of testcases input
while(testcases counter doesn't reach 0 )
take string input
call your function for answer for input and print
decrement testcases counter
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.