Created
January 25, 2020 13:16
-
-
Save dashsaurabh/bb7db3de7ec5f9a20fb3bbb5b63747e3 to your computer and use it in GitHub Desktop.
Reverse Only Letter in a String
This file contains 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 {string} | |
* "ab-cd" should become "dc-ba" | |
*/ | |
var reverseOnlyLetters = function(S) { | |
let stack = []; | |
let resultArr = []; | |
let letters = /^[A-Za-z]+$/; | |
for(let i = 0;i<S.length;i++){ | |
if(S[i].match(letters)){ | |
stack.push(S[i]) | |
} | |
} | |
for(let i = 0;i<S.length;i++) { | |
if(S[i].match(letters)){ | |
resultArr.push(stack.pop()) | |
}else{ | |
resultArr.push(S[i]) | |
} | |
} | |
return resultArr.join(''); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment