Created
December 2, 2019 11:57
-
-
Save musale/8c9e5702caa537b98b44a7c421f63a30 to your computer and use it in GitHub Desktop.
Solution to a string comparison question
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
package main | |
// Write a function that takes an array containing two strings where | |
// each string represents keypresses separated by commas. For this | |
// problem, a keypress can be either a printable character or a | |
// backspace (represented by -B). Your function should determine if | |
// the two strings of keypresses are equivalent. | |
import ( | |
"fmt" | |
"reflect" | |
"strings" | |
) | |
// EquivalentKeypresses - evaluates if 2 strings of keypresses are the same | |
func EquivalentKeypresses(strArr []string) bool { | |
arr1 := strings.Split(strArr[0], ",") | |
arr2 := strings.Split(strArr[1], ",") | |
newArr1 := reduceArray(arr1) | |
newArr2 := reduceArray(arr2) | |
return reflect.DeepEqual(newArr1, newArr2) | |
} | |
// reduceArray - deletes a character from an array of string characters | |
// if it encounters the character "-B" | |
func reduceArray(arr []string) []string { | |
var newArr []string | |
for _, ch := range arr { | |
if ch == "-B" && len(arr) > 0 { | |
newArr = newArr[:len(newArr)-1] | |
fmt.Println(newArr, len(newArr)) | |
} else { | |
newArr = append(newArr, ch) | |
} | |
} | |
return newArr | |
} | |
func main() { | |
v := []string{"c,a,r,d", "c,a,-B,r,d"} | |
fmt.Println(EquivalentKeypresses(v)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment