Last active
April 6, 2018 02:20
-
-
Save kavitshah8/48f78fe43f145ec2d0fb to your computer and use it in GitHub Desktop.
Strings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
function braces(values) { | |
var i; | |
var result = []; | |
var len = values.length; | |
for (i = 0; i < len; i++) { | |
if (isBalanced(values[i])) { | |
result.push('YES'); | |
} else { | |
result.push('NO'); | |
} | |
} | |
return result; | |
} | |
function isBalanced(str) { | |
var i, ch; | |
var bracketsMap = new Map(); | |
bracketsMap.set(']', '['); | |
bracketsMap.set('}', '{'); | |
bracketsMap.set(')', '('); | |
// Use the spread operator to transform a map into a 2D key-value Array. | |
var closingBrackets = [...bracketsMap.keys()]; | |
var openingBrackets = [...bracketsMap.values()]; | |
var temp = []; | |
var len = str.length; | |
for (i = 0; i < len; i++) { | |
ch = str[i]; | |
if (openingBrackets.indexOf(ch) > -1) { | |
temp.push(ch); | |
} else if (closingBrackets.indexOf(ch) > -1) { | |
var expectedBracket = bracketsMap.get(ch); | |
if (temp.length === 0 || (temp.pop() !== expectedBracket)) { | |
return false; | |
} | |
} else { | |
// Ignore the characters which do not match valid Brackets symbol | |
continue; | |
} | |
} | |
return (temp.length === 0); | |
} | |
var i1 = [ | |
"{}[]()", | |
"{[}]" | |
]; | |
var i2 = [ | |
"{[}]", | |
"[{()()}({[]})]({}[({})])((((((()[])){}))[]{{{({({({{{{{{}}}}}})})})}}}))[][][]", | |
"{}[]()" | |
]; | |
console.log(braces(i1)); // ["YES","NO"] | |
console.log(braces(i2)); // ["NO","YES","YES"] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {string} s | |
* @return {boolean} | |
*/ | |
function isValid(str) { | |
if (str.length <= 1) | |
return false | |
let matchingOpeningBracket, ch | |
let stack = [] | |
let openingBrackets = ['[', '{', '('] | |
let closingBrackets = [']', '}', ')'] | |
for (let i = 0; i < str.length; i++) { | |
ch = str[i] | |
if (closingBrackets.indexOf(ch) > -1) { | |
matchingOpeningBracket = openingBrackets[closingBrackets.indexOf(ch)] | |
if (stack.length == 0 || (stack.pop() != matchingOpeningBracket)) { | |
return false | |
} | |
} else { | |
stack.push(ch) | |
} | |
} | |
return (stack.length == 0) | |
}; | |
console.log(isValid("([)]")) // false | |
console.log(isValid("()")) // true | |
console.log(isValid("{}[]()")) // true | |
console.log(isValid("{[}]")) // false | |
console.log(isValid("{[}]")) // false | |
console.log(isValid("[{()()}({[]})]({}[({})])((((((()[])){}))[]{{{({({({{{{{{}}}}}})})})}}}))[][][]")) // true | |
console.log(isValid("{}[]()")) // true |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const combine = (instr, outstr, index) => { | |
for (var i = index; i < instr.length; i++) { | |
// append the character | |
outstr = outstr.concat(instr.charAt(i)); | |
//print the result | |
console.log(outstr); | |
// make a recursive call at i + 1 | |
combine(instr, outstr, i + 1); | |
// remove the character added in the first step | |
outstr = outstr.substr(0, outstr.length - 1); | |
} | |
}; | |
combine("abc", "", 0); // a, ab, abc, ac, b, bc, c | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function stringCompression (str) { | |
if (str.length ==0) { | |
console.log('Please enter valid string.'); | |
return; | |
} | |
var output = ''; | |
var count = 0; | |
for (var i = 0; i < str.length; i++) { | |
count++; | |
if (str[i] != str[i+1]) { | |
output += str[i] + count; | |
count = 0; | |
} | |
} | |
console.log(output); | |
} | |
stringCompression(''); //Please enter valid string. | |
stringCompression('aaaa'); //a4 | |
stringCompression('aaaabbc'); //a4b2c1 | |
stringCompression('aaaabbcaabb'); //a4b2c1a2b2 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function createFrequencyAnalysis(str) { | |
var charFrequency = {}; | |
Array.prototype.forEach.call(str, function(ch) { | |
charFrequency[ch] ? charFrequency[ch]++ : charFrequency[ch] = 1; | |
}); | |
return charFrequency; | |
} | |
console.log(createFrequencyAnalysis("foo bar")); // {" ": 1, a: 1, b: 1, f: 1, o: 2, r: 1} | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
function findUnique(str) { | |
var i, ch; | |
var len = str.length; | |
var freqMap = new Map(); | |
var uniq = ''; | |
for (i = 0; i < len; i++) { | |
ch = str[i]; | |
if (!freqMap.get(ch)) { | |
freqMap.set(ch, 1); | |
} else { | |
freqMap.set(ch, -1); | |
} | |
} | |
freqMap.forEach(function(val, key) { | |
if (val == 1) { | |
uniq += key; | |
} | |
}); | |
return uniq; | |
} | |
console.log(findUnique('bar')); // bar | |
console.log(findUnique('foo')); // f | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function isAnagram (str1, str2) { | |
if (str1.length !== str2.length) { | |
return false; | |
} | |
var sortStr1 = str1.split('').sort().join(''); | |
var sortStr2 = str2.split('').sort().join(''); | |
return (sortStr1 === sortStr2); | |
} | |
console.log(isAnagram('dog','god')); // true | |
console.log(isAnagram('foo','bar')); // false | |
console.log(isAnagram('foo','fooo')); // false | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function isAnagram (str1, str2) { | |
if (str1.length !== str2.length) { | |
return false; | |
} | |
// create a character count for the string | |
var str1Count = {}; | |
Array.prototype.forEach.call(str1, function(ch) { | |
str1Count[ch] = str1Count[ch] ? 1 + str1Count[ch] : 1; | |
}); | |
// compare the character count with the second string | |
var str2len = str2.length; | |
for (var i = 0; i < str2len; i++) { | |
if(!str1Count[str2[i]]) { | |
return false; | |
} else { | |
str1Count[str2[i]] -= 1; | |
} | |
} | |
return true; | |
} | |
console.log(isAnagram('dog','god')); // true | |
console.log(isAnagram('foo','bar')); // false | |
console.log(isAnagram('foo','fooo')); // false | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
function isUnique(str) { | |
var i, ch; | |
var len = str.length; | |
if (len > 127) { | |
return false; | |
} | |
for (i = 0; i < len; i++) { | |
ch = str[i]; | |
if (str.indexOf(ch, i + 1) > -1) { | |
return false; | |
} | |
} | |
return true; | |
} | |
console.log(isUnique('bar')); // true | |
console.log(isUnique('foo')); // false | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
function isomorphic (str1, str2) { | |
var len1 = str1.length; | |
var arr2 = str2.split(' '); | |
if (len1 != arr2.length) { | |
return false; | |
} | |
var chMap = {}; | |
for (var i = 0; i < len1; i++) { | |
if (!chMap[str1[i]]) { | |
chMap[str1[i]] = arr2[i]; | |
} else if ( chMap[str1[i]] !== arr2[i]) { | |
return false; | |
} | |
} | |
return true; | |
} | |
console.log(isomorphic('abba', 'dog cat cat dog')); // true | |
console.log(isomorphic('abba', 'dog cat cat fish')); // false | |
console.log(isomorphic('aaaa', 'dog cat cat dog')); // false | |
console.log(isomorphic('abba', 'dog dog dog dog')); // true | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
function isomorphic (str1, str2) { | |
var len1 = str1.length; | |
if (len1 != str2.length) { | |
console.log('Both strings have different lenghts'); | |
return false; | |
} | |
var chMap = {}; | |
for (var i = 0; i < len1; i++) { | |
if (!chMap[str1[i]]) { | |
chMap[str1[i]] = str2[i]; | |
} else if (chMap[str1[i]] !== str2[i]) { | |
console.log('Both strings differ in maaping at index ' + i); | |
return false; | |
} | |
} | |
return true; | |
} | |
console.log(isomorphic('foo','bar')); // false | |
console.log(isomorphic('foo','baa')); // true | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
function isWordBreakable (s, dict, answer) { | |
// console.log(s + ' ' + answer); | |
var strLen = s.length; | |
if (strLen === 0) { | |
console.log(answer); | |
return true; | |
} else { | |
var prefix = ''; | |
for (var i = 0; i < strLen; i++) { | |
// add one char at a time | |
prefix += s.charAt(i); | |
// check if prefix exists in dictionary | |
// if (dict.includes(prefix)) { // Array.prototype.includes() is an ES7 Feature | |
if (dict.indexOf(prefix) > -1) { | |
//add prefix to the answer and make a recursive call | |
answer += prefix + ' '; | |
var suffix = s.slice(i + 1); | |
if (isWordBreakable(suffix, dict, answer)) { | |
return true; | |
} | |
} | |
//console.log(prefix + ' backtrack'); | |
} | |
} | |
} | |
var inputStr = 'Ihavedog'; | |
var inputDict = ['I', 'have', 'ha' , 'am', 'this', 'dog']; | |
if (!isWordBreakable(inputStr, inputDict, '')) { | |
console.log('String can not broken.'); | |
} // I ha have dog | |
var inputStr2 = 'Ihavesdog'; | |
if (!isWordBreakable(inputStr2, inputDict, '')) { | |
console.log('String can not broken.'); | |
} // String can not broken. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
function isWordBreakable (s, dict, answer) { | |
var strLen = s.length; | |
// console.log(s + ' ' + answer); | |
if (strLen === 0) { | |
console.log(answer); | |
return true; | |
} else { | |
var i = 0; | |
var prefix = ''; | |
while (i < strLen) { | |
// add one char at a time | |
prefix += s.charAt(i); | |
// check if prefix exists in dictionary | |
// if (dict.includes(prefix)) { // Array.prototype.includes() is an ES7 Feature | |
if (dict.indexOf(prefix) > -1) { | |
//add prefix to the answer and make a recursive call | |
answer += prefix + ' '; | |
var suffix = s.slice(i + 1); | |
if (isWordBreakable(suffix, dict, answer)) { | |
return true; | |
} else { | |
//console.log(prefix + ' backtrack'); | |
i++; | |
} | |
} else { | |
i++; | |
} | |
} | |
return false; | |
} | |
} | |
var inputStr = 'Ihavedog'; | |
var inputDict = ['I', 'have', 'ha' , 'am', 'this', 'dog']; | |
if (!isWordBreakable(inputStr, inputDict, '')) { | |
console.log('String can not broken.'); | |
} // I ha have dog | |
var inputStr2 = 'Ihavesdog'; | |
if (!isWordBreakable(inputStr2, inputDict, '')) { | |
console.log('String can not broken.'); | |
} // String can not broken. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function lengthOfLongestSubstring(s) { | |
if (s.length <= 1) | |
return s.length | |
let lookup = new Map() | |
let len = s.length | |
let max = 0 | |
let start = 0 | |
for (let i = 0; i < len; i++) { | |
let c = s.charAt(i) | |
if (lookup.has(c) && lookup.get(c) >= start) { | |
start = lookup.get(c) + 1; // Read the logic in the notes above | |
} | |
lookup.set(c, i) | |
max = Math.max(max, i - start + 1) | |
} | |
return max; | |
} | |
console.log(lengthOfLongestSubstring('OBAMACARE')) // 4 | |
console.log(lengthOfLongestSubstring('ABBA')) // 2 | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
function createFrequencyAnalysis(str) { | |
var charFrequency = {}; | |
Array.prototype.forEach.call(str, function(ch) { | |
charFrequency[ch] ? charFrequency[ch]++ : charFrequency[ch] = 1; | |
}); | |
return charFrequency; | |
} | |
function reArrange (str) { | |
var freqMap = createFrequencyAnalysis(str); | |
var strLength = str.length; | |
var characters = Object.keys(freqMap); | |
var output = new Array(strLength); | |
var i = 0; | |
var j = 0; | |
var k = 0; | |
var charFreq = 0; | |
var numberOfChar = characters.length; | |
for (i = 0; i < numberOfChar; i++) { | |
charFreq = freqMap[characters[i]]; | |
if (charFreq >= ((strLength / 2 ) + 1)) { | |
console.log('No valid output'); | |
return; | |
} | |
for (k = 0; k < charFreq; k++) { | |
// If reached at the end of an array, wrap the array and start from the begining with odd (1, 3, 5 ...) indexes | |
if (j > strLength) { | |
j = 1; | |
} | |
output[j] = characters[i]; | |
j += 2; | |
} | |
} | |
return output.join(''); | |
} | |
console.log(reArrange('aaabc')); // abaca | |
console.log(reArrange('aa')); // No valid output | |
console.log(reArrange('aaaabc')); // No valid output | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function replaceAllSpaces (str) { | |
// creates an array of the given string seperated by comma | |
var arr = str.split(' '); | |
// creates a string of the given array joined by %20 | |
var modifiedStr = arr.join('%20'); | |
return modifiedStr; | |
} | |
console.log(replaceAllSpaces('Mr Johny Walkser')); // Mr%20Johny%20Walkser | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function reverseSentence(sentence) { | |
return sentence.split(' ').reverse().join(' '); | |
} | |
var sentence = 'This is cat'; | |
console.log(reverseSentence(sentence)); // 'cat is This' | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function reverseString(str) { | |
var revStr = ''; | |
var strLength = str.length; | |
for (var i = strLength - 1; i >= 0 ; i--) { | |
revStr += str[i]; | |
} | |
return revStr; | |
} | |
console.log(reverseString('Hello')); // olleH | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function reverseString(str) { | |
return str.split('').reverse().join(''); | |
} | |
console.log(reverseString('Hello')); // olleH | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment