Longest palindrome in a string - javascript

I wrote the following function to find the longest palindrome in a string. It works fine but it won't work for words like "noon" or "redder". I fiddled around and changed the first line in the for loop from:
var oddPal = centeredPalindrome(i, i);
to
var oddPal = centeredPalindrome(i-1, i);
and now it works, but I'm not clear on why. My intuition is that if you are checking an odd-length palindrome it will have one extra character in the beginning (I whiteboarded it out and that's the conclusion I came to). Am I on the right track with my reasoning?
var longestPalindrome = function(string) {
var length = string.length;
var result = "";
var centeredPalindrome = function(left, right) {
while (left >= 0 && right < length && string[left] === string[right]) {
//expand in each direction.
left--;
right++;
}
return string.slice(left + 1, right);
};
for (var i = 0; i < length - 1; i++) {
var oddPal = centeredPalindrome(i, i);
var evenPal = centeredPalindrome(i, i);
if (oddPal.length > result.length)
result = oddPal;
if (evenPal.length > result.length)
result = evenPal;
}
return "the palindrome is: " + result + " and its length is: " + result.length;
};
UPDATE:
After Paul's awesome answer, I think it makes sense to change both variables for clarity:
var oddPal = centeredPalindrome(i-1, i + 1);
var evenPal = centeredPalindrome(i, i+1);

You have it backwards - if you output the "odd" palindromes (with your fix) you'll find they're actually even-length.
Imagine "noon", starting at the first "o" (left and right). That matches, then you move them both - now you're comparing the first "n" to the second "o". No good. But with the fix, you start out comparing both "o"s, and then move to both "n"s.
Example (with the var oddPal = centeredPalindrome(i-1, i); fix):
var longestPalindrome = function(string) {
var length = string.length;
var result = "";
var centeredPalindrome = function(left, right) {
while (left >= 0 && right < length && string[left] === string[right]) {
//expand in each direction.
left--;
right++;
}
return string.slice(left + 1, right);
};
for (var i = 0; i < length - 1; i++) {
var oddPal = centeredPalindrome(i, i + 1);
var evenPal = centeredPalindrome(i, i);
if (oddPal.length > 1)
console.log("oddPal: " + oddPal);
if (evenPal.length > 1)
console.log("evenPal: " + evenPal);
if (oddPal.length > result.length)
result = oddPal;
if (evenPal.length > result.length)
result = evenPal;
}
return "the palindrome is: " + result + " and its length is: " + result.length;
};
console.log(
longestPalindrome("nan noon is redder")
);

This will be optimal if the largest palindrome is found earlier.
Once its found it will exit both loops.
function isPalindrome(s) {
//var rev = s.replace(/\s/g,"").split('').reverse().join(''); //to remove space
var rev = s.split('').reverse().join('');
return s == rev;
}
function longestPalind(s) {
var maxp_length = 0,
maxp = '';
for (var i = 0; i < s.length; i++) {
var subs = s.substr(i, s.length);
if (subs.length <= maxp_length) break; //Stop Loop for smaller strings
for (var j = subs.length; j >= 0; j--) {
var sub_subs = subs.substr(0, j);
if (sub_subs.length <= maxp_length) break; // Stop loop for smaller strings
if (isPalindrome(sub_subs)) {
maxp_length = sub_subs.length;
maxp = sub_subs;
}
}
}
return maxp;
}

Here is another take on the subject.
Checks to make sure the string provided is not a palindrome. If it is then we are done. ( Best Case )
Worst case 0(n^2)
link to
gist
Use of dynamic programming. Break each problem out into its own method, then take the solutions of each problem and add them together to get the answer.
class Palindrome {
constructor(chars){
this.palindrome = chars;
this.table = new Object();
this.longestPalindrome = null;
this.longestPalindromeLength = 0;
if(!this.isTheStringAPalindrome()){
this.initialSetupOfTableStructure();
}
}
isTheStringAPalindrome(){
const reverse = [...this.palindrome].reverse().join('');
if(this.palindrome === reverse){
this.longestPalindrome = this.palindrome;
this.longestPalindromeLength = this.palindrome.length;
console.log('pal is longest', );
return true;
}
}
initialSetupOfTableStructure(){
for(let i = 0; i < this.palindrome.length; i++){
for(let k = 0; k < this.palindrome.length; k++){
this.table[`${i},${k}`] = false;
}
}
this.setIndividualsAsPalindromes();
}
setIndividualsAsPalindromes(){
for(let i = 0; i < this.palindrome.length; i++){
this.table[`${i},${i}`] = true;
}
this.setDoubleLettersPlaindrome();
}
setDoubleLettersPlaindrome(){
for(let i = 0; i < this.palindrome.length; i++){
const firstSubstring = this.palindrome.substring(i, i + 1);
const secondSubstring = this.palindrome.substring(i+1, i + 2);
if(firstSubstring === secondSubstring){
this.table[`${i},${i + 1}`] = true;
if(this.longestPalindromeLength < 2){
this.longestPalindrome = firstSubstring + secondSubstring;
this.longestPalindromeLength = 2;
}
}
}
this.setAnyPalindromLengthGreaterThan2();
}
setAnyPalindromLengthGreaterThan2(){
for(let k = 3; k <= this.palindrome.length; k++){
for(let i = 0; i <= this.palindrome.length - k; i++){
const j = i + k - 1;
const tableAtIJ = this.table[`${i+1},${j-1}`];
const stringToCompare = this.palindrome.substring(i, j +1);
const firstLetterInstringToCompare = stringToCompare[0];
const lastLetterInstringToCompare = [...stringToCompare].reverse()[0];
if(tableAtIJ && firstLetterInstringToCompare === lastLetterInstringToCompare){
this.table[`${i},${j}`] = true;
if(this.longestPalindromeLength < stringToCompare.length){
this.longestPalindrome = stringToCompare;
this.longestPalindromeLength = stringToCompare.length;
}
}
}
}
}
printLongestPalindrome(){
console.log('Logest Palindrome', this.longestPalindrome);
console.log('from /n', this.palindrome );
}
toString(){
console.log('palindrome', this.palindrome);
console.log(this.table)
}
}
// const palindrome = new Palindrome('lollolkidding');
// const palindrome = new Palindrome('acbaabca');
const palindrome = new Palindrome('acbaabad');
palindrome.printLongestPalindrome();
//palindrome.toString();

function longestPalindrome(str){
var arr = str.split("");
var endArr = [];
for(var i = 0; i < arr.length; i++){
var temp = "";
temp = arr[i];
for(var j = i + 1; j < arr.length; j++){
temp += arr[j];
if(temp.length > 2 && temp === temp.split("").reverse().join("")){
endArr.push(temp);
}
}
}
var count = 0;
var longestPalindrome = "";
for(var i = 0; i < endArr.length; i++){
if(count >= endArr[i].length){
longestPalindrome = endArr[i-1];
}
else{
count = endArr[i].length;
}
}
console.log(endArr);
console.log(longestPalindrome);
return longestPalindrome;
}
longestPalindrome("abracadabra"));

let str = "HYTBCABADEFGHABCDEDCBAGHTFYW12345678987654321ZWETYGDE";
let rev = str.split("").reverse().join("").trim();
let len = str.length;
let a="";
let result = [];
for(let i = 0 ; i < len ; i++){
for(let j = len ; j > i ; j--){
a = rev.slice(i,j);
if(str.includes(a)){
result.push(a);
break;
}
}
}
result.sort((a,b) => { return b.length - a.length})
let logPol = result.find((value)=>{
return value === value.split('').reverse().join('') && value.length > 1
})
console.log(logPol);

function longest_palindrome(s) {
if (s === "") {
return "";
}
let arr = [];
let _s = s.split("");
for (let i = 0; i < _s.length; i++) {
for (let j = 0; j < _s.length; j++) {
let word = _s.slice(0, j + 1).join("");
let rev_word = _s
.slice(0, j + 1)
.reverse()
.join("");
if (word === rev_word) {
arr.push(word);
}
}
_s.splice(0, 1);
}
let _arr = arr.sort((a, b) => a.length - b.length);
for (let i = 0; i < _arr.length; i++) {
if (_arr[arr.length - 1].length === _arr[i].length) {
return _arr[i];
}
}
}
longest_palindrome('bbaaacc')
//This code will give you the first longest palindrome substring into the string

var longestPalindrome = function(string) {
var length = string.length;
var result = "";
var centeredPalindrome = function(left, right) {
while (left >= 0 && right < length && string[left] === string[right]) {
//expand in each direction.
left--;
right++;
}
return string.slice(left + 1, right);
};
for (var i = 0; i < length - 1; i++) {
var oddPal = centeredPalindrome(i, i + 1);
var evenPal = centeredPalindrome(i, i);
if (oddPal.length > 1)
console.log("oddPal: " + oddPal);
if (evenPal.length > 1)
console.log("evenPal: " + evenPal);
if (oddPal.length > result.length)
result = oddPal;
if (evenPal.length > result.length)
result = evenPal;
}
return "the palindrome is: " + result + " and its length is: " + result.length;
};
console.log(longestPalindrome("n"));
This will give wrong output so this condition need to be taken care where there is only one character.

public string LongestPalindrome(string s) {
return LongestPalindromeSol(s, 0, s.Length-1);
}
public static string LongestPalindromeSol(string s1, int start, int end)
{
if (start > end)
{
return string.Empty;
}
if (start == end)
{
char ch = s1[start];
string s = string.Empty;
var res = s.Insert(0, ch.ToString());
return res;
}
if (s1[start] == s1[end])
{
char ch = s1[start];
var res = LongestPalindromeSol(s1, start + 1, end - 1);
res = res.Insert(0, ch.ToString());
res = res.Insert(res.Length, ch.ToString());
return res;
}
else
{
var str1 = LongestPalindromeSol(s1, start, end - 1);
var str2 = LongestPalindromeSol(s1, start, end - 1);
if (str1.Length > str2.Length)
{
return str1;
}
else
{
return str2;
}
}
}

This is in JS ES6. much simpler and works for almost all words .. Ive tried radar, redder, noon etc.
const findPalindrome = (input) => {
let temp = input.split('')
let rev = temp.reverse().join('')
if(input == rev){
console.log('Palindrome', input.length)
}
}
//i/p : redder
// "Palindrome" 6

Related

Reverse Javascript Capitalized

enter image description here
enter image description here
How to make observe the Capital word behavior ?
source code :
enter code here
document.getElementById("btnReverse").onclick = function () {
reverse();
};
String.prototype.replaceAt = function (index, replacement) {
if (index >= this.length) {
return this.valueOf();
}
return this.substring(0, index) + replacement + this.substring(index + 1);
};
function reverseWord(word) {
let wordLength = word.length;
let reversedWord = word;
for (let j = 0; j < wordLength / 2; j++) {
let temp = reversedWord[j];
reversedWord = reversedWord.replaceAt(j, word[wordLength - 1 - j]);
reversedWord = reversedWord.replaceAt(wordLength - 1 - j, temp);
}
return reversedWord;
}
function reverse() {
let text = document.getElementById("text").value;
let splittedText = text.split(" ");
let reversedWords = [];
for (let i = 0; i < splittedText.length; i++) {
let word = splittedText[i];
let reversedWord = reverseWord(word);
reversedWords.push(reversedWord);
}
document.getElementById("demo").innerHTML = reversedWords.join(" ");
}`enter code here`
This function re-capitalize a reversed word:
function reCapitalize(word) {
// Check if last letter is an uppercase
// If so, return the word with first letter converted to capital
if (word[word.length - 1] === word[word.length - 1].toUpperCase())
return word[0].toUpperCase() + word.toLowerCase().substring(1, word.length);
// return word unchanged
return word;
}
So your reverse function will be like this:
function reverseWord(word) {
let wordLength = word.length;
let reversedWord = word;
for (let j = 0; j < wordLength / 2; j++) {
let temp = reversedWord[j];
reversedWord = reversedWord.replaceAt(j, word[wordLength - 1 - j]);
reversedWord = reversedWord.replaceAt(wordLength - 1 - j, temp);
}
return reCapitalize(reversedWord);
}
Change the below line of reverse() method and use textContent instead of value.
let text = document.getElementById("text").textContent;
document.getElementById("btnReverse").onclick = function () {
reverse();
};
String.prototype.replaceAt = function (index, replacement) {
if (index >= this.length) {
return this.valueOf();
}
return this.substring(0, index) + replacement + this.substring(index + 1);
};
function reverseWord(word) {
let wordLength = word.length;
let reversedWord = word;
for (let j = 0; j < wordLength / 2; j++) {
let temp = reversedWord[j];
let rightChar = word[wordLength - 1 - j];
if(j === 0 && wordLength > 1 && word[j].toUpperCase() === word[j]) {
temp = temp.toLowerCase();
rightChar = rightChar.toUpperCase();
}
reversedWord = reversedWord.replaceAt(j, rightChar);
reversedWord = reversedWord.replaceAt(wordLength - 1 - j, temp);
}
return reversedWord;
}
function reverse() {
let text = document.getElementById("text").textContent;
let splittedText = text.split(" ");
let reversedWords = [];
for (let i = 0; i < splittedText.length; i++) {
let word = splittedText[i];
let reversedWord = reverseWord(word);
reversedWords.push(reversedWord);
}
document.getElementById("demo").innerHTML = reversedWords.join(" ");
}
<html>
<head></head>
<body>
<div>
<button id="btnReverse">Reverse</button>
<div id="text">I am A Great human</div>
<div id="demo"></div>
</div>
</body>
</html>

Reverse the word in a string with the same order in javascript without using the array functions except .length

I want reverse the string with the same order. We should not use the Array functions like split(), .reverse() and .join(). but we can use array.length.
Here i am attached my code. How to achieve that thing more efficiently.
var str = "i am javascript";
// result "i ma tpircsavaj"
function reverseString(myStr){
var strlen = myStr.length, result = "", reverseStr = "", reverseStrArr = [];
for(var i = strlen-1; i >= 0; i--){
reverseStr += myStr[i];
}
for(var j = 0; j < strlen; j++){
if(reverseStr[j] == " "){
reverseStrArr.push(result);
result = "";
}else{
result += reverseStr[j];
if(j + 1 == strlen){
reverseStrArr.push(result);
result = "";
}
}
}
for(var k=reverseStrArr.length - 1; k >= 0; k--){
result += reverseStrArr[k] + " "
}
console.log(result);
}
reverseString(str);
Use 2 pointers: i to indicate the current position and j to indicate the start index of the current word. Add the reversed of current word char by char when space.
Don't be fooled by the nested loops, the complexity is the same as yours: O(n) and somehow cleaner for me.
var string = "i love javascript and the whole world!"
var result = ""
var i = j = 0
var l = string.length
while (i++ < l) {
var k = i
if (string[i] === " " || (i === l - 1) && k++) {
while (--k >= j) result += string[k]
j = i + 1
result += " "
}
}
result = result && result.slice(0, -1) || ""
console.log(result)
You could take a loop, collect the characters of a word and reverse the word.
function reverse(string) {
var reversed = '';
while (reversed.length !== string.length) {
reversed = string[reversed.length] + reversed;
}
return reversed;
}
var string = "i am javascript",
temp = '',
result = '',
i = 0;
while (i < string.length) {
if (string[i] === ' ') {
result += (result && ' ') + reverse(temp);
temp = '';
} else {
temp += string[i];
}
i++;
}
if (temp) result += (result && ' ') + reverse(temp);
console.log(result);
An approach from the end.
function reverse(string) {
var reversed = '';
while (reversed.length !== string.length) {
reversed = string[reversed.length] + reversed;
}
return reversed;
}
var string = "i am javascript",
temp = '',
result = '',
i = string.length;
while (i--) {
if (string[i] === ' ') {
result = ' ' + reverse(temp) + result;
temp = '';
} else {
temp = string[i] + temp;
}
}
if (temp) result = reverse(temp) + result;
console.log(result);
function reverseStr(str) {
var ret = "";
for (var i = 0; i < str.length; i++) {
ret = str[i] + ret;
}
return ret;
}
function doIt(str) {
var ret = "", cur = "";
for (var i = 0; i < str.length; i++) {
var c = str.charAt(i);
if (c == ' ' || c == '.') {
ret += reverseStr(cur) + c;
cur = "";
} else {
cur += c;
}
}
ret += reverseStr(cur);
return ret;
}
console.log(doIt('Reverse the word in a string with the same order in javascript without using the array functions except .length'));
function reverse(word) {
if (word.length > 1) {
var newWord = '';
for (j = word.length-1; j >= 0; j--) {
newWord += word[j];
}
return newWord + ' ';
} else {
return word + ' ';
}
}
var text = "i am javascript";
var words = text.split(' ');
var result = '';
for (i = 0; i < words.length; i++) {
result += reverse(words[i]);
}
console.log(result);

Why does this function return " '\'1\'' " according to codewars?

So I'm trying to solve this codewars problem (https://www.codewars.com/kata/5518a860a73e708c0a000027/train/javascript), but instead of my function returning a regular string like "1", it apparently returns something like " '\'1\'' ", according to codewars. Why is this? My code is below:
function lastDigit(as){
var product = "1";
for(var i = as.length - 1; i >= 0; i--){
var num = as[i]
//console.log(num)
//console.log(bigPower(num.toString(), product))
product = bigPower(as[i].toString(), product);
}
var prodArr = product.split("");
console.log(prodArr[prodArr.length - 1].toString());
return prodArr[prodArr.length - 1].toString();
}
function bigPower(base, exponent){
var product = base;
for(var i = 1; i < parseInt(exponent); i++){
product = multiply(product.toString(), base.toString());
}
return product;
}
function multiply(a, b) {
const product = Array(a.length+b.length).fill(0);
for (let i = a.length; i--; null) {
let carry = 0;
for (let j = b.length; j--; null) {
product[1+i+j] += carry + a[i]*b[j];
carry = Math.floor(product[1+i+j] / 10);
product[1+i+j] = product[1+i+j] % 10;
}
product[i] += carry;
}
return product.join("").replace(/^0*(\d)/, "$1");
}
Use parseInt function in the return statement to parse the string and return as an integer.
return parseInt(prodArr[prodArr.length - 1].toString());
function lastDigit(as){
var product = "1";
for(var i = as.length - 1; i >= 0; i--){
var num = as[i]
product = bigPower(as[i].toString(), product);
}
var prodArr = product.split("");
return parseInt(prodArr[prodArr.length - 1].toString());
}
function bigPower(base, exponent){
var product = base;
for(var i = 1; i < parseInt(exponent); i++){
product = multiply(product.toString(), base.toString());
}
return product;
}
function multiply(a, b) {
const product = Array(a.length+b.length).fill(0);
for (let i = a.length; i--; null) {
let carry = 0;
for (let j = b.length; j--; null) {
product[1+i+j] += carry + a[i]*b[j];
carry = Math.floor(product[1+i+j] / 10);
product[1+i+j] = product[1+i+j] % 10;
}
product[i] += carry;
}
return product.join("").replace(/^0*(\d)/, "$1");
}
console.log(lastDigit([3, 4, 2]))

longest substring of non repeating characters javascript

The problems asks "given a string, find the longest non-repeating sub-string without repeating characters". I am a little stumped why returning my code is not working for the string "dvdf" for example. Here is my code :
function lengthOfLongestSubstring(check) {
var letters = check.split("");
var max = 0;
var result = [];
for (var i = 0; i < letters.length; i++) {
var start = i
if (result.indexOf(letters[i]) === -1) {
result.push(letters[i])
} else {
i = i - 1
result = []
}
if (max === 0 || max < result.length) {
max = result.length
}
}
return max
}
This implementation gives the correct result for "dvdf".
It adds characters to current_string while there is no duplicate. When you find a duplicate cut current_string to the point of the duplicate. max is the max length current_string had at any time. This logic seems correct to me so I think it's correct.
function lengthOfLongestSubstring(string) {
var max = 0, current_string = "", i, char, pos;
for (i = 0; i < string.length; i += 1) {
char = string.charAt(i);
pos = current_string.indexOf(char);
if (pos !== -1) {
// cut "dv" to "v" when you see another "d"
current_string = current_string.substr(pos + 1);
}
current_string += char;
max = Math.max(max, current_string.length);
}
return max;
}
lengthOfLongestSubstring("dvdf"); // 3
The value of current_string in each round is "", "d", "dv", "vd", "vdf".
By replacing the result array with a map storing the last index for each encountered character, you can modify the loop body to jump back to one after the last index of an identical character and continue your search from there instead of just restarting from the current position via currently i = i - 1 which fails in cases such as 'dvdf':
Below is your code with changes to accommodate a map in place of an array:
function lengthOfLongestSubstring(check) {
var letters = check.split("");
var max = 0;
var result = new Map();
var start = 0;
for (var i = 0; i < letters.length; i++) {
if (!result.has(letters[i])) {
result.set(letters[i], i);
} else {
i = result.get(letters[i]);
result.clear();
}
if (max < result.size) {
max = result.size;
}
}
return max;
}
// Example:
console.log(lengthOfLongestSubstring("dvdf")); // 3
Here's a solution using Sliding window and HashMap.
var lengthOfLongestSubstring = function(str) {
if (!!!str.length || typeof str !== 'string') return 0;
if (str.length == 1) return 1;
let hashTable = {};
let longestSubstringLength = 0;
let start = 0;
for (let i = 0; i < str.length; i++) {
if (hashTable[str[i]] !== undefined && hashTable[str[i]] >= start) {
start = hashTable[str[i]] + 1;
}
hashTable[str[i]] = i;
longestSubstringLength = Math.max(longestSubstringLength, (i - start + 1))
}
return longestSubstringLength;
}
I figured out an easier solution:
function longestSubstring(str) {
let left = 0;
let max = 0;
let result = new Set();
for (let r = 0; r < str.length; r++) {
//The code will check for an existing item on the set
// If found, all the previously saved items will be deleted
// the set will return to being empty
while (result.has(str[r])) {
result.delete(str[left]);
left += 1;
}
result.add(str[r]);
max = Math.max(max, r - left + 1);
}
console.log(result);
return max;
}
console.log(longestSubstring('abcabccbc')); //3
Today (January 7th, 2021) this was the Leetcode question of the day. I initially used a solution very similar to the selected answer. Performance was okay but after reviewing the answer solution documentation I rewrote my answer using the sliding window technique (examples were only in Java and Python) since I was curious about how much of a performance improvement this would result in. It is slightly more performant (144ms versus 160ms) and has a lower memory footprint (42mb versus 44.9mb):
function lengthOfLongestSubstring(s: string): number {
let stringLength = s.length;
let maxLength = 0;
const charMap = new Map();
let pos = 0;
for (let i = 0; i < stringLength; i++) {
if (charMap.has(s[i])) {
pos = Math.max(charMap.get(s[i]), pos);
}
maxLength = Math.max(maxLength, i - pos + 1);
charMap.set(s[i], i + 1);
}
return maxLength;
}
console.log(lengthOfLongestSubstring("dvdf"));
Try this:
function lengthOfLongestSubstring (str) {
const map = new Map();
let max = 0;
let left = 0;
for (let right = 0; right < str.length; right++) {
const char = str[right];
if (map.get(char) >= left) left = map.get(char) + 1;
else max = Math.max(max, right - left + 1);
map.set(char, right);
}
return max;
}
You can try this:
function lengthOfLongestSubstring(str) {
let longest = "";
for (let i = 0; i < str.length; i++) {
if (longest.includes(str[i])) {
return longest.length
} else {
longest += str[i];
}
}
return longest.length;
}
console.log(lengthOfLongestSubstring("abcabcbb"));
console.log(lengthOfLongestSubstring("bbbbb"));
console.log(lengthOfLongestSubstring("abcdef"));
console.log(lengthOfLongestSubstring(""));
reset i to i -1 is incorrect. you need another loop inside the for loop. you try something like this (i didn't check the index carefully).
function lengthOfLongestSubstring(check){
var letters = check.split("");
var max = 0;
for (var i = 0; i < letters.length; i++) {
var result = [];
var j = i;
for(;j < letters.length; j++) {
if (result.indexOf(letters[j]) === -1) {
result.push(letters[j]);
} else {
break;
}
}
if(j - i > max) {
max = j - i;
}
}
return max;
}
You can try sliding window pattern to solve this problem.
function lengthOfLongestSubstring(str) {
let longest = 0;
let longestStr = "";
let seen = {};
let start = 0;
let next = 0;
while (next < str.length) {
// Take current character from string
let char = str[next];
// If current character is already present in map
if (seen[char]) {
// Check if start index is greater than current character's last index
start = Math.max(start, seen[char]);
}
// If new substring is longer than older
if (longest < next - start + 1) {
longest = next - start + 1;
// Take slice of longer substring
longestStr = str.slice(start, next + 1);
}
// Update current characters index
seen[char] = next + 1;
// Move to next character
next++;
}
console.log(str, "->", longestStr, "->", longest);
return longest;
}
lengthOfLongestSubstring("dvdfvev");
lengthOfLongestSubstring("hello");
lengthOfLongestSubstring("1212312344");
Find Longest Unique Substring using Map Method
var str = "aaabcbdeaf";
var start = 0;
var map = new Map();
var maxLength = 0;
var longStr = '';
for(next =0; next< str.length ; next++){
if(map.has(str[next])){
map.set(str[next],map.get(str[next])+1);
start = Math.max(start,map.get(str[next]));
}
if(maxLength < next-start+1){
maxLength = next-start+1;
longStr = str.slice(start,next+1);
}
map.set(str[next],next);
}
console.log(longStr);
You can try something like that:
function maxSubstring(s) {
const array = []
const lengthS = s.length
const pusher = (value) => {
if (value !== '') {
if (array.length > 0) {
if (array.indexOf(value) === -1) {
array.push(value)
}
} else {
array.push(value)
}
}
}
pusher(s)
for (const [index, value] of s.split('').entries()) {
let length = lengthS
let string = s
const indexO = s.indexOf(value)
pusher(value)
while (length > indexO) {
pusher(string.slice(index-1, length + 1))
length = --length
}
string = s.slice(index, lengthS)
}
array.sort()
return array.pop()
}
console.log(maxSubstring('banana'))
console.log(maxSubstring('fgjashore'))
console.log(maxSubstring('xyzabcd'))
Find Longest unique substring without using MAP(). Just simple slice().
The same can be used to return longest unique string.
Just replace "return max => return str"
const string = "dvdf";
var lengthOfLongestSubstring = function() {
if(string.length == 1) return 1;
if(string.length == 0) return 0;
let max = 0,i = 0, str = "";
while(i < string.length){
const index = str.indexOf(string.charAt(i));
if(index > -1) {
// s = "fiterm".slice(1,4) => ite
str = str.slice(index + 1, string.length);
}
str += string.charAt(i);
max = Math.max(str.length, max);
i++;
}
return max;
};
Logest unqiue substring:
function lengthOfLongestSubstring(s) {
if(s.length < 2) {
return s.length;
}
let longestLength = 1;
let currentStr = '';
for(let i=0 ; i < s.length ; i++){
if(currentStr.includes(s.charAt(i))){
let firstSeen = currentStr.indexOf(s.charAt(i));
currentStr = currentStr.substring(firstSeen+1,currentStr.length);
}
currentStr += s.charAt(i);
longestLength = Math.max(currentStr.length,longestLength);
}
return longestLength;
};
One liner with reduce method.
const subStrOfUniqueChar = str => [...str].reduce((p,c) => ( p.includes(c) ? (p += c, p.substr(p.indexOf(c)+1)) : p += c),'');
console.log(subStrOfUniqueChar('dvdf').length);
function lengthOfLongestSubstring(s: string): number {
const arr = s.split("");
let longest = 0;
const set: Set<string> = new Set();
for (let i = 0; i < arr.length; i++) {
set.add(arr[i]);
let tryIndex = i + 1;
while (arr[tryIndex] && !set.has(arr[tryIndex])) {
set.add(arr[tryIndex]);
tryIndex++;
}
if (set.size > longest) {
longest = set.size;
}
set.clear();
}
return longest;
}
I wanted to toss my hat in this ring because I feel like I've found a pretty creative solution to this. No if/else blocks are needed as the substring.indexOf() will attempt to find the matching string character in the array and delete the indexes of the array up to, and including, the match (+1). If an indexOf() call finds no match it will return a -1, which added to +1 becomes a .splice(0,0) which will remove nothing. The final Math check factors in the last character addition in the loop to determine which outcome is higher.
const findSubstring = string => {
let substring = [];
let maxCount = 0;
for (let i = 0; i < string.length; i++) {
maxCount = Math.max(substring.length, maxCount);
substring.splice(0, substring.indexOf(string[i]) + 1);
substring.push(string[i]);
}
maxCount = Math.max(substring.length, maxCount);
return maxCount;
}
uses sliding window concept
function lengthOfLongestSubstring(s) {
var letters = s.split("");
var subStr = "";
var result = [];
var len = 0;
let maxLen = 0;
for (var i = 0; i < letters.length; i++) {
const position = result.indexOf(letters[i]);
if (position === -1) {
result.push(letters[i]);
len += 1;
} else if (letters[i]) {
result = result.splice(position + 1);
len = result.length + 1;
result.push(letters[i]);
}
maxLen = len > maxLen ? len : maxLen;
}
return maxLen;
}
console.log(lengthOfLongestSubstring(" "));
Sliding Window Technique O(n)
you can use hash or Map in
loop through string char
Maintain dictionary of unique char
if char exist in memory take clear hash update the count in longest variable and clear count
start from first repeated char + 1 again.
var lengthOfLongestSubstring = function(s) {
if(s.length<2) return s.length;
let longest = 0;
let count=0;
let hash={}
for (let i = 0; i < s.length; i++) {
//If char exist in hash
if(hash[s[i]]!=undefined){
i=hash[s[i]];
hash={}
longest = Math.max(longest, count);
count = 0;
}else{
hash[s[i]]=i
count = count+1;
}
}
return Math.max(longest, count);
};
console.log(lengthOfLongestSubstring("abcabcbb"))
console.log(lengthOfLongestSubstring("au"))

Longest substring in alphabetical order Javascript

Seeing all the people talking about longest substring in alphabetical order in Python, I have decided to try it in JS.
The function should look for the longest substring inside a given string, where letters are ordered alphabetically.
Here is what I have:
var s = 'azcbobobegghakl'
function substringChecker(s) {
var longestSub = "";
for (var i = 0; i < s.length; i++) {
var count = 0;
var currSub = "";
while((i+count)<=s.length){
var curr = i+count;
var next = curr+1;
var prev = curr-1;
if(curr !== s.length-1) {
if(s[curr] <= s[next]){
currSub += s[curr]
} else {
break;
}
} else {
if(s[curr]>s[prev]) {
currSub += s[curr];
}
}
count++;
}
if(currSub.length >= longestSub.length) {
longestSub = currSub;
}
};
return longestSub;
}
var result = substringChecker(s);;
console.log(result);
The funny thing it works great for all test cases I can come up with, but this one. The result should be "beggh" but it is "begg" instead. Why is the h not showing up, what am I missing?
The algorithm can be linear, I think you are overcomplicating it placing loops inside loops.
I would use something like
function substringChecker(s) {
var longestSub = "",
length = 0,
start = 0,
prev = s[0];
for (var i = 1; i <= s.length; ++i) {
if(i == s.length || s[i] < prev) {
if(length < i-start) {
longestSub = s.substring(start, i);
length = i-start;
}
start = i;
}
prev = s[i];
};
return longestSub;
}
document.write(substringChecker('azcbobobegghakl'));
first I made list of A-z
then check each letter and compare it with the next letter and save it in subString and...
function longest(str) {
//handle the case str is just one letter
if (str.length === 1) return str;
// create a list of alphabet A to Z
const alphabets = [...Array(26)].map(_ => String.fromCharCode(i++), (i = 97));
let longString = "";
let subSting = "";
for (let x = 0; x < str.length; x++) {
let char = str.charAt(x);
const nextChar = str.charAt(x + 1);
let charIndex = alphabets.findIndex(alphabet => alphabet === char);
let nextCharIndex = alphabets.findIndex(alphabet => alphabet === nextChar);
if (nextCharIndex >= charIndex) {
subSting = subSting + nextChar;
} else {
if (!subSting.length) {
subSting = subSting + char;
}
longString = subSting.length > longString.length ? subSting : longString;
subSting = "";
}
}
return longString;
}
console.log(longest("zyba"));

Categories