Created
September 16, 2021 14:49
-
-
Save liron-navon/2e6a05aa80a6121c23dbb6a832eb15a8 to your computer and use it in GitHub Desktop.
Solution for - CodeSignal - Reverse In Parentheses
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
// 1. Find the pairs of parentheses | |
function getStartAndEndIndexes(inputString) { | |
const regularExpression = /\([a-zA-Z]*?\)/; | |
const execData = regularExpression.exec(inputString); | |
if(!execData) { | |
return null; | |
} | |
const startIndex = execData.index; | |
const endIndex = execData.index + execData[0].length - 1; | |
return {startIndex, endIndex} | |
} | |
// 2. Find the part of the string we need to reverse | |
function reverseParentheses(startIndex, endIndex, inputString) { | |
// before the parenthesis | |
const startSegmant = inputString.substring(0, startIndex); | |
// the parenthesis | |
const parenthesisSegmant = | |
inputString.substring(startIndex +1, endIndex); | |
// after the parenthesis | |
const endSegmant = | |
inputString.substring(endIndex + 1, inputString.length); | |
return startSegmant + reverse(parenthesisSegmant) + endSegmant; | |
} | |
// 3. Reverse the string | |
function reverse(string) { | |
return string.split('').reverse().join(''); | |
} | |
// 4. Repeat until all parentheses are replaced | |
function reverseInParentheses(inputString) { | |
let indexes = getStartAndEndIndexes(inputString); | |
while(indexes) { | |
const {startIndex, endIndex} = indexes; | |
const newString = | |
reverseParentheses(startIndex, endIndex, inputString); | |
inputString = reverseInParentheses(newString); | |
indexes = getStartAndEndIndexes(inputString); | |
} | |
return inputString; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Solution for Swift
func solution(inputString: String) -> String {
var result = ""
var stack = String
for letter in inputString {
if letter == "(" {
stack.append("")
} else if letter == ")" {
guard let last = stack.popLast() else { continue }
let reversedString = String(last.reversed())
if let lastStack = stack.last {
stack[stack.count - 1] = lastStack + reversedString
} else {
result += reversedString
}
} else if let lastStack = stack.last {
stack[stack.count - 1] += String(letter)
} else {
result += String(letter)
}
}
return result
}