function longestWord(string) {
var str = string.split(" ");
var longest = 0;
var word = null;
for (var i = 0; i < str.length - 1; i++) {
if (longest < str[i].length) {
longest = str[i].length;
word = str[i];
}
}
return word;
}
When I call longestWord("Pride and Prejudice"), it returns 'Pride' and not 'Prejudice' which is the longest word... why? I checked some other similar questions, but the solutions looked a lot like my code.
That's because you're not comparing all the items in the array, you leave out the last one.
for (var i = 0; i < str.length - 1; i++)
should be
for (var i = 0; i < str.length; i++)
or
for (var i = 0; i <= str.length - 1; i++)
One advantage to taking a functional approach to such problems is that you don't even have to keep count
See MDN Array.reduce for more info. (note: reduce needs shim for IE8)
function longer(champ, contender) {
return (contender.length > champ.length) ? contender : champ;
}
function longestWord(str) {
var words = str.split(' ');
return words.reduce(longer);
}
console.log(longestWord("The quick brown fox jumped over the lazy dogs"));
Here this is your solution with a forEach, this will help you avoid the error in the future
function longestWord(string) {
var str = string.split(" ");
var longest = 0;
var word = null;
str.forEach(function(str) {
if (longest < str.length) {
longest = str.length;
word = str;
}
});
return word;
}
console.log(longestWord("pride and prejudice"));
Your original problem was just the str.length - 1 should have just been str.length, originally you wouldn't have gotten to the last element of the array
You have a -1 in your condition, it never even scans it:
for (var i = 0; i < str.length - 1; i++) {
Should be:
for (var i = 0; i < str.length; i++) {
Demo: http://jsfiddle.net/LfgFk/
The index is going up to str.length -1:
for (var i = 0; i < str.length - 1; i++) {
So the last word is not processed.
Try with: longestWord("Pride AAAAAAAAAAAAAAAAAAAAAAAAA and Prejudice"). You'll see it works (returns AAAAAAAAAAAAAAAAAAAAAAAAA).
In case you're in doubt, the simplest way to fix it is removing the -1 from the for loop.
for (var i = 0; i < str.length; i++) {
Check a demo with both versions (the problematic and the fixed): link here.
You can simplify your code with a library like Lo-Dash:
function longestWord(string) {
var words = string.split(' ');
return _.max(words, function(word) { return word.length; });
}
ForEach is faster in FF but slower in Chrome,
but for loop with the cached length and function apply/call is quite faster in both FF and chrome.
Hope the below code helps:
function getLongest (arrStr) {
var longest = 0, word;
for(var i=0 , len = arrStr.length ; i < len ; i++){
if(longest < arrStr[i].length) {
longest = arrStr[i].length;
word = arrStr[i];
}
}
return word;
}
function isLongest (str) {
var arrayStr = str.split(' ');
return function(fn) {
return fn.apply(this,[arrayStr]);
}
}
isLongest("hello aaaaaaaaaaaaaaaaaaaaaaaaa bbb")(getLongest); //aaaaaaaaaaaaaaaaaaaaaaaaa
for (var i = 0; i < str.length - 1; i++)
to
for (var i = 0; i <= str.length - 1; i++)
OR
for (var i = 0; i < str.length; i++)
does this solve the problem??
function longestWord(string) {
var str = string.split(" ");
var longest = 0;
var word = null;
for (var i = 0; i <= str.length - 1; i++) {
if (longest < str[i].length) {
longest = str[i].length;
word = str[i];
}
}
return word;
}
document.write(longestWord("pride and prejudice"));
I find that the .map method here helps a lot (this is if you want the character count of the word, not the word itself):
function findLongestWord(str) {
var array = str.split(/\s+/);
var wordLength = array.map(function(i) {
return i.length;
});
var largest = Math.max.apply(Math, wordLength);
return largest;
}
I will refer you to this awesome article which defines three ways:
1 - Find the Longest Word With a FOR Loop
function findLongestWord(str) {
var strSplit = str.split(' ');
var longestWord = 0;
for(var i = 0; i < strSplit.length; i++){
if(strSplit[i].length > longestWord){
longestWord = strSplit[i].length;
}
}
return longestWord;
}
findLongestWord("The quick brown fox jumped over the lazy dog");
2 - Find the Longest Word With the sort() Method
function findLongestWord(str) {
var longestWord = str.split(' ').sort(function(a, b) { return b.length - a.length; });
return longestWord[0].length;
}
findLongestWord("The quick brown fox jumped over the lazy dog");
3 - Find the Longest Word With the reduce() Method
function findLongestWord(str) {
var longestWord = str.split(' ').reduce(function(longest, currentWord) {
return currentWord.length > longest.length ? currentWord : longest;
}, "");
return longestWord.length;
}
findLongestWord("The quick brown fox jumped over the lazy dog");
Of course, it returns the length of the biggest word if you want to get the string, just get rid of the length in return part.
function longestWord(sentence){
var arr = sentence.match(/[a-z]+/gi);
arr.sort(function(a, b){
return b.length - a.length;
});
return arr[0];
}
longestWord('hello man##$%');
// ==> output: hello
function LongestWord(sen) {
// code goes here
const wordsArray = sen.split('').map(c => (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c<='9')? c : ' ').join('').split(' ').filter(item => item !== '');
wordsArray.sort((a, b) => a.length < b.length);
return wordsArray[0];
}
Is there a specific reason
for (var i = 0; i < str.length - 1; i++)
isn't
for (var i = 0; i < str.length - 1; i++)
That seems like it could be the cause.
You need to use:
for (var i=0;i<=str.length - 1; i++)
That way it will scan the entire phrase
Thanks everyone, this is the fixed code:
function longestWord(string) {
var str = string.split(" ");
var longest = 0;
var word = null;
for (var i = 0; i < str.length; i++) {
var checkedLetters = "";
for (var j = 0; j < str[i].length; j++) {
if (/[a-zA-Z]/.test(str[i][j])) {
checkedLetters += str[i][j];
}
if (longest < checkedLetters.length) {
longest = checkedLetters.length;
word = checkedLetters;
}
}
}
return word;
}
This seems to be the easiest way to do this.
function longestWord(string) {
var str = string.split(" ");
var longest = 0;
var word = null;
str.forEach(function(str) {
if (longest < str.length) {
longest = str.length;
word = str;
}
});
return word;
}
I would say using the forEach loop is the most understandable version
function longestWord(sen) {
big_word = ""
words = sen.split(" ")
words.forEach(function(word){
if (word.length > big_word.length){
big_word = word
};
});
return big_word
};
I think this is more easy
function findLongestWord(str) {
var longestStr = 0;
for (var x=0;x<str.split(' ').length;x++){
if (longestStr < str.split(' ')[x].length){
longestStr = str.split(' ')[x].length;
}
}
return longestStr;
}
Here is one other way to solve it.
function findLongestWord(str) {
var result = [];
var one = str.split(" ");
for (var i = 0; i < one.length; i++) {
result[i] = one[i].length;
result.reverse().sort(function(a,b) {
return b-a;
});
}
return result[0];
}
Using the sort() method,this sorts the elements of an array by some ordering criterion and then returns the length of the first element of this array and hence the longest word.
function longest(string){
var longestWord = string.split(' ').sort(function(a,b){
return b.length - a.length;
});
return longestWord[0];
}
TRY THIS
function longest(string) {
var str = string.split(" ");
var longest = 0;
var word = null;
for (var i = 0; i <= str.length - 1; i++) {
if (longest < str[i].length) {
longest = str[i].length;
word = str[i];
}
}
return word;
}
Another method is by using sort:
function longestWord(string) {
let longest = 0;
let str = str.split(" ").sort((word1,word2)=>{
});
return str[0].length;
}
longestWord('I love Python ')
Code below will find the largest word and its length from a string.
Code is in plain JavaScript and html.
function findLongestWord() {
var str = document.getElementById('inputText').value;
calculateLength(str);
}
function calculateLength(str) {
var substring = str.split(" ");
var minChar = '';
for (var i = 0; i <= substring.length - 1; i++) {
if (substring[i].length >= minChar.length) {
minChar = substring[i];
}
}
document.getElementById('longChar').innerHTML = 'Longest Word: ' + minChar;
document.getElementById('longCharLength').innerHTML = 'Longest Word length: ' + minChar.length;
}
<!doctype html>
<html lang="en">
<head>
</head>
<body>
<input type="text" id="inputText"> <br/>
<button onclick=findLongestWord()>Click to find longest word</button> <br/>
<div id="longChar"></div> <br/>
<div id="longCharLength"></div>
</body>
<script src="longestWord.js"></script>
</html>
function findLongestWord(str) {
let stringArray = str.split(" ");
stringArray.sort(function(a, b){
return a.split('').length < b.split('').length;
})
return stringArray[0];
}
findLongestWord("The quick brown fox jumped over the lazy dog");
function sortNumber(a, b) {
return a - b;
}
function findLongestWordLength(str) {
var split = str.split(" ");
var arr=[];
for(var i=0;i<split.length;i++){
arr.push(split[i].length);
}
arr.sort(sortNumber);
console.log(arr[arr.length-1]);
return(arr[arr.length-1]);
}
findLongestWordLength("What if we try a super-long word such as otorhinolaryngology");
const longestWord = string =>
{
stringArray = string.split(' ').sort(
(a,b) => b.length - a.length)
let longestArray= stringArray.filter( word => word.length === stringArray[0].length )
if(longestArray.length === 1){
console.log(longestArray[0])
}
else
{
console.log(longestArray)
}
}
longestWord("Pride and Prejudice")
// My simple solution.
const findLongestWordLength = str => {
let array = str.split(" ");
let longest = 0;
array.map(e => {
if (e.length > longest) {
longest = e.length;
}
})
return longest;
}
Solutions above are incomplete. What if there r 2 or more words that have same length. here is a better solution:
longest = str => {
let words = str.split(" ");
let size = 0;
let max = [""];
for (let i = 0; i < words.length; i++) {
if (words[i].length > size) {
size = words[i].length;
}
if (max[max.length - 1].length < words[i].length) {
max = [];
max.push(words[i]);
} else {
max = [...max, words[i]];
}
}
return max;
};
For error checking in question, refer this answer
Longest word in String
Using for/forEach loop
function longestWord(str){
const words = str.split(' ');
let longWord = "";
words.forEach((word) => {
if(word.length > longWord.length) { longWord = word }
})
return longWord;
}
Using sort
function longestWord(str) {
return str.split(' ')
.sort((a, b) => b.length - a.length)[0];
}
Using reduce
function longestWord(str){
return str.split(' ')
.reduce((maxWord, curWord) => curWord.length > maxWord.length ? curWord : maxWord );
}
// for loop
function longestWord1(str){
const words = str.split(' ');
let longWord = "";
words.forEach((word) => {
if(word.length > longWord.length) { longWord = word }
})
return longWord;
}
// sort
function longestWord2(str) {
return str.split(' ').sort((a, b) => b.length - a.length)[0];
}
// reduce
function longestWord3(str){
return str.split(' ').reduce((maxWord, curWord) => curWord.length > maxWord.length ? curWord : maxWord );
}
let text;
text = "What if we try a super-long word such as otorhinolaryngology";
console.log(longestWord1(text));//=> "otorhinolaryngology"
text = "";
console.log(longestWord2(text));//=> ""
text = "What "
console.log(longestWord3(text));//=> "What"
text = "What is pen?"
console.log(longestWord1(text));//=> "What"
text = "three four five six twenty one"
console.log(longestWord2(text));//=> "twenty"
text = ("The quick brown fox jumped over the lazy dog")
console.log(longestWord3(text));//=> "jumped"
Related
I'm trying to do a reverse-word script in javascript. I have written this function, but it does not work and I can't understand why. What is wrong? Is there any other way to do it?
function inverser(x)
{
var newString ="";
var index=(x.length - 1);
var y=0;
for (var i=index ; i>=0 ; i--)
{
x[i] = newString [y++];
}
return (newString );
}
console.log(inverser("test"));
You need to add to concatenate newString instead of trying to assign an index to it. The logic of your function should be
newString[y++] += x[i];
Link to code
when you use newString[y++], newString is still empty string and doesn't have cell 1 or 2 or 3 .... and can't assign string to this cell.
simply if you remove y variable and make some move on line 9 can get answer.
here the code worked for me:
function inverser(x) {
var newString = "";
var index = (x.length - 1);
for (var i = index; i >= 0; i--)
{
newString += x[i];
}
return (newString);
}
Use reverse():
function inverser(x)
{
return x.split("").reverse().join("");
}
It's simple if you don't need build in function, please comment, i will update my answer :)
Update
The assignment statements are wrong in your code, it should have been:
newString += x[i];
"use strict";
function wordReverse() {
const str1 = "God is Good";
const str2 = str1.split(" ");
//console.log(str2);
const reverseWord = [];
const len = str2.length;
//console.log(len);
for (let i = len - 1; i >= 0; i--) {
reverseWord.push(str2[i]);
}
return reverseWord;
}
console.log(wordReverse().join(" "));
const word = "reverse";
const reverseString = (str) => str.split("").reverse().join("");
reverseString(word);
function reverseWord(str) {
const splittedString = str.split(" ");
const wordreverse = [];
const len = splittedString.length;
for (let i = len - 1; i >= 0; i--) {
wordreverse.push(splittedString[i]);
}
return wordreverse.join(" ");
}
function reverseWord(str) {
const splittedString = str.split(" ");
const wordreverse = [];
const len = splittedString.length;
for (let i = len - 1; i >= 0; i--) {
wordreverse.push(splittedString[i]);
}
return wordreverse.join(" ");
}
console.log(reverseWord("hello world"))
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"))
My code was work well with string like "The quick brown fox jumped over the lazy dog".
But not work with string like "Google do a barrel roll".
It says problem is "TypeError undefined is not an object(evaluating 'Astr[i].length') ".
function findLongestWord(str) {
var Astr = str.split(" ");
var t = Astr[0].length;
var Al = Astr.length;
var j = 0;
for(var i =1; i < t;i++)
{
if(t < Astr[i].length)
{
t = Astr[i].length;
j = i;
}
}
str = Astr[j];
return str.length;
}
findLongestWord("Google do a barrel roll");
Here is one way of improving your function:
var str = 'Google do a barrel roll';
function findLongestWord(str) {
var Astr = str.split(' ');
if (!Astr.length) {
throw new Error('findLongestWord(): no words in str');
}
var t = Astr[0].length;
var Al = Astr.length;
var j = 0;
for(var i = 0; i < Al; i++)
{
if(t < Astr[i].length)
{
t = Astr[i].length;
j = i;
}
}
str = Astr[j];
return str.length;
}
findLongestWord(str);
//=> 6
You can also do something like this (which is a little easier to understand):
str.split(' ').reduce(function(longest, cur) {
return (cur.length > longest.length) ? cur : longest;
}, '');
//=> Google
you have problem with the variables in your 'for' loop.
As you can see, you split the array and get the length of the first member in the array
So basicly you get the first word length instead of the word count
var Astr = str.split(" ");
var t = Astr[0].length;
Here you can see that you use 't' (the first word length) as your loop bounds.
for(var i =1; i < t;i++)
Keep your code simple & readable this way it will be maintainable.
function findLongestWord(str) {
var words = str.split(" ");
var words_count = words.length;
var longest_word_length = 0;
for(var i = 0; i < words_count; i++){
if(longest_word_length < words[i].length){
longest_word_length = words[i].length;
}
}
return longest_word_length;
}
findLongestWord("Google do a barrel roll");
Note that you always can use short-hand functions for that
function findLongestWord(str) {
return str.split(' ').reduce(function(longest, cur) {
return (cur.length > longest.length) ? cur : longest;
}, '').length;
}
findLongestWord("Google do a barrel roll");
function findLongestWord(str)
{var arr=[];
arr=str.split(' ');
arr=arr.sort(function(a,b)
{
return b.length-a.length; /*sorting the array in decending order of
lengths of each word*/
});
var st=arr[0]; /* obviously the first element of the array will
have longest length.*/
return st.length;
}
findLongestWord("Google do a barrel roll");
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"));
I have to make a function in JavaScript that removes all duplicated letters in a string. So far I've been able to do this: If I have the word "anaconda" it shows me as a result "anaconda" when it should show "cod". Here is my code:
function find_unique_characters( string ){
var unique='';
for(var i=0; i<string.length; i++){
if(unique.indexOf(string[i])==-1){
unique += string[i];
}
}
return unique;
}
console.log(find_unique_characters('baraban'));
We can also now clean things up using filter method:
function removeDuplicateCharacters(string) {
return string
.split('')
.filter(function(item, pos, self) {
return self.indexOf(item) == pos;
})
.join('');
}
console.log(removeDuplicateCharacters('baraban'));
Working example:
function find_unique_characters(str) {
var unique = '';
for (var i = 0; i < str.length; i++) {
if (str.lastIndexOf(str[i]) == str.indexOf(str[i])) {
unique += str[i];
}
}
return unique;
}
console.log(find_unique_characters('baraban'));
console.log(find_unique_characters('anaconda'));
If you only want to return characters that appear occur once in a string, check if their last occurrence is at the same position as their first occurrence.
Your code was returning all characters in the string at least once, instead of only returning characters that occur no more than once. but obviously you know that already, otherwise there wouldn't be a question ;-)
Just wanted to add my solution for fun:
function removeDoubles(string) {
var mapping = {};
var newString = '';
for (var i = 0; i < string.length; i++) {
if (!(string[i] in mapping)) {
newString += string[i];
mapping[string[i]] = true;
}
}
return newString;
}
With lodash:
_.uniq('baraban').join(''); // returns 'barn'
You can put character as parameter which want to remove as unique like this
function find_unique_characters(str, char){
return [...new Set(str.split(char))].join(char);
}
function find_unique_characters(str, char){
return [...new Set(str.split(char))].join(char);
}
let result = find_unique_characters("aaaha ok yet?", "a");
console.log(result);
//One simple way to remove redundecy of Char in String
var char = "aaavsvvssff"; //Input string
var rst=char.charAt(0);
for(var i=1;i<char.length;i++){
var isExist = rst.search(char.charAt(i));
isExist >=0 ?0:(rst += char.charAt(i) );
}
console.log(JSON.stringify(rst)); //output string : avsf
For strings (in one line)
removeDuplicatesStr = str => [...new Set(str)].join('');
For arrays (in one line)
removeDuplicatesArr = arr => [...new Set(arr)]
Using Set:
removeDuplicates = str => [...new Set(str)].join('');
Thanks to David comment below.
DEMO
function find_unique_characters( string ){
unique=[];
while(string.length>0){
var char = string.charAt(0);
var re = new RegExp(char,"g");
if (string.match(re).length===1) unique.push(char);
string=string.replace(re,"");
}
return unique.join("");
}
console.log(find_unique_characters('baraban')); // rn
console.log(find_unique_characters('anaconda')); //cod
var str = 'anaconda'.split('');
var rmDup = str.filter(function(val, i, str){
return str.lastIndexOf(val) === str.indexOf(val);
});
console.log(rmDup); //prints ["c", "o", "d"]
Please verify here: https://jsfiddle.net/jmgy8eg9/1/
Using Set() and destructuring twice is shorter:
const str = 'aaaaaaaabbbbbbbbbbbbbcdeeeeefggggg';
const unique = [...new Set([...str])].join('');
console.log(unique);
Yet another way to remove all letters that appear more than once:
function find_unique_characters( string ) {
var mapping = {};
for(var i = 0; i < string.length; i++) {
var letter = string[i].toString();
mapping[letter] = mapping[letter] + 1 || 1;
}
var unique = '';
for (var letter in mapping) {
if (mapping[letter] === 1)
unique += letter;
}
return unique;
}
Live test case.
Explanation: you loop once over all the characters in the string, mapping each character to the amount of times it occurred in the string. Then you iterate over the items (letters that appeared in the string) and pick only those which appeared only once.
function removeDup(str) {
var arOut = [];
for (var i=0; i < str.length; i++) {
var c = str.charAt(i);
if (c === '_') continue;
if (str.indexOf(c, i+1) === -1) {
arOut.push(c);
}
else {
var rx = new RegExp(c, "g");
str = str.replace(rx, '_');
}
}
return arOut.join('');
}
I have FF/Chrome, on which this works:
var h={};
"anaconda".split("").
map(function(c){h[c] |= 0; h[c]++; return c}).
filter(function(c){return h[c] == 1}).
join("")
Which you can reuse if you write a function like:
function nonRepeaters(s) {
var h={};
return s.split("").
map(function(c){h[c] |= 0; h[c]++; return c}).
filter(function(c){return h[c] == 1}).
join("");
}
For older browsers that lack map, filter etc, I'm guessing that it could be emulated by jQuery or prototype...
This code worked for me on removing duplicate(repeated) characters from a string (even if its words separated by space)
Link: Working Sample JSFiddle
/* This assumes you have trim the string and checked if it empty */
function RemoveDuplicateChars(str) {
var curr_index = 0;
var curr_char;
var strSplit;
var found_first;
while (curr_char != '') {
curr_char = str.charAt(curr_index);
/* Ignore spaces */
if (curr_char == ' ') {
curr_index++;
continue;
}
strSplit = str.split('');
found_first = false;
for (var i=0;i<strSplit.length;i++) {
if(str.charAt(i) == curr_char && !found_first)
found_first = true;
else if (str.charAt(i) == curr_char && found_first) {
/* Remove it from the string */
str = setCharAt(str,i,'');
}
}
curr_index++;
}
return str;
}
function setCharAt(str,index,chr) {
if(index > str.length-1) return str;
return str.substr(0,index) + chr + str.substr(index+1);
}
Here's what I used - haven't tested it for spaces or special characters, but should work fine for pure strings:
function uniquereduce(instring){
outstring = ''
instringarray = instring.split('')
used = {}
for (var i = 0; i < instringarray.length; i++) {
if(!used[instringarray[i]]){
used[instringarray[i]] = true
outstring += instringarray[i]
}
}
return outstring
}
Just came across a similar issue (finding the duplicates). Essentially, use a hash to keep track of the character occurrence counts, and build a new string with the "one-hit wonders":
function oneHitWonders(input) {
var a = input.split('');
var l = a.length;
var i = 0;
var h = {};
var r = "";
while (i < l) {
h[a[i]] = (h[a[i]] || 0) + 1;
i += 1;
}
for (var c in h) {
if (h[c] === 1) {
r += c;
}
}
return r;
}
Usage:
var a = "anaconda";
var b = oneHitWonders(a); // b === "cod"
Try this code, it works :)
var str="anaconda";
Array.prototype.map.call(str,
(obj,i)=>{
if(str.indexOf(obj,i+1)==-1 && str.lastIndexOf(obj,i-1)==-1){
return obj;
}
}
).join("");
//output: "cod"
This should work using Regex ;
NOTE: Actually, i dont know how this regex works ,but i knew its 'shorthand' ,
so,i would have Explain to you better about meaning of this /(.+)(?=.*?\1)/g;.
this regex only return to me the duplicated character in an array ,so i looped through it to got the length of the repeated characters .but this does not work for a special characters like "#" "_" "-", but its give you expected result ; including those special characters if any
function removeDuplicates(str){
var REPEATED_CHARS_REGEX = /(.+)(?=.*?\1)/g;
var res = str.match(REPEATED_CHARS_REGEX);
var word = res.slice(0,1);
var raw = res.slice(1);
var together = new String (word+raw);
var fer = together.toString();
var length = fer.length;
// my sorted duplicate;
var result = '';
for(var i = 0; i < str.length; i++) {
if(result.indexOf(str[i]) < 0) {
result += str[i];
}
}
return {uniques: result,duplicates: length};
} removeDuplicates('anaconda')
The regular expression /([a-zA-Z])\1+$/ is looking for:
([a-zA-Z]]) - A letter which it captures in the first group; then
\1+ - immediately following it one or more copies of that letter; then
$ - the end of the string.
Changing it to /([a-zA-Z]).*?\1/ instead searches for:
([a-zA-Z]) - A letter which it captures in the first group; then
.*? - zero or more characters (the ? denotes as few as possible); until
\1 - it finds a repeat of the first matched character.
I have 3 loopless, one-line approaches to this.
Approach 1 - removes duplicates, and preserves original character order:
var str = "anaconda";
var newstr = str.replace(new RegExp("[^"+str.split("").sort().join("").replace(/(.)\1+/g, "").replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&")+"]","g"),"");
//cod
Approach 2 - removes duplicates but does NOT preserve character order, but may be faster than Approach 1 because it uses less Regular Expressions:
var str = "anaconda";
var newstr = str.split("").sort().join("").replace(/(.)\1+/g, "");
//cdo
Approach 3 - removes duplicates, but keeps the unique values (also does not preserve character order):
var str = "anaconda";
var newstr = str.split("").sort().join("").replace(/(.)(?=.*\1)/g, "");
//acdno
function removeduplicate(str) {
let map = new Map();
// n
for (let i = 0; i < str.length; i++) {
if (map.has(str[i])) {
map.set(str[i], map.get(str[i]) + 1);
} else {
map.set(str[i], 1);
}
}
let res = '';
for (let i = 0; i < str.length; i++) {
if (map.get(str[i]) === 1) {
res += str[i];
}
}
// o (2n) - > O(n)
// space o(n)
return res;
}
If you want your function to just return you a unique set of characters in your argument, this piece of code might come in handy.
Here, you can also check for non-unique values which are being recorded in 'nonUnique' titled array:
function remDups(str){
if(!str.length)
return '';
var obj = {};
var unique = [];
var notUnique = [];
for(var i = 0; i < str.length; i++){
obj[str[i]] = (obj[str[i]] || 0) + 1;
}
Object.keys(obj).filter(function(el,ind){
if(obj[el] === 1){
unique+=el;
}
else if(obj[el] > 1){
notUnique+=el;
}
});
return unique;
}
console.log(remDups('anaconda')); //prints 'cod'
If you want to return the set of characters with their just one-time occurrences in the passed string, following piece of code might come in handy:
function remDups(str){
if(!str.length)
return '';
var s = str.split('');
var obj = {};
for(var i = 0; i < s.length; i++){
obj[s[i]] = (obj[s[i]] || 0) + 1;
}
return Object.keys(obj).join('');
}
console.log(remDups('anaconda')); //prints 'ancod'
function removeDuplicates(str) {
var result = "";
var freq = {};
for(i=0;i<str.length;i++){
let char = str[i];
if(freq[char]) {
freq[char]++;
} else {
freq[char] =1
result +=char;
}
}
return result;
}
console.log(("anaconda").split('').sort().join('').replace(/(.)\1+/g, ""));
By this, you can do it in one line.
output: 'cdo'
function removeDuplicates(string){
return string.split('').filter((item, pos, self)=> self.indexOf(item) == pos).join('');
}
the filter will remove all characters has seen before using the index of item and position of the current element
Method 1 : one Simple way with just includes JS- function
var data = 'sssssddddddddddfffffff';
var ary = [];
var item = '';
for (const index in data) {
if (!ary.includes(data[index])) {
ary[index] = data[index];
item += data[index];
}
}
console.log(item);
Method 2 : Yes we can make this possible without using JavaScript function :
var name = 'sssssddddddddddfffffff';
let i = 0;
let newarry = [];
for (let singlestr of name) {
newarry[i] = singlestr;
i++;
}
// now we have new Array and length of string
length = i;
function getLocation(recArray, item, arrayLength) {
firstLaction = -1;
for (let i = 0; i < arrayLength; i++) {
if (recArray[i] === item) {
firstLaction = i;
break;
}
}
return firstLaction;
}
let finalString = '';
for (let b = 0; b < length; b++) {
const result = getLocation(newarry, newarry[b], length);
if (result === b) {
finalString += newarry[b];
}
}
console.log(finalString); // sdf
// Try this way
const str = 'anaconda';
const printUniqueChar = str => {
const strArr = str.split("");
const uniqueArray = strArr.filter(el => {
return strArr.indexOf(el) === strArr.lastIndexOf(el);
});
return uniqueArray.join("");
};
console.log(printUniqueChar(str)); // output-> cod
function RemDuplchar(str)
{
var index={},uniq='',i=0;
while(i<str.length)
{
if (!index[str[i]])
{
index[str[i]]=true;
uniq=uniq+str[i];
}
i++;
}
return uniq;
}
We can remove the duplicate or similar elements in string using for loop and extracting string methods like slice, substring, substr
Example if you want to remove duplicate elements such as aababbafabbb:
var data = document.getElementById("id").value
for(var i = 0; i < data.length; i++)
{
for(var j = i + 1; j < data.length; j++)
{
if(data.charAt(i)==data.charAt(j))
{
data = data.substring(0, j) + data.substring(j + 1);
j = j - 1;
console.log(data);
}
}
}
Please let me know if you want some additional information.