Skip to content

Instantly share code, notes, and snippets.

@piotrek1543
Last active December 20, 2023 23:04
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save piotrek1543/bed76895b05bc65ac0d92d7e25bcfcc7 to your computer and use it in GitHub Desktop.
Save piotrek1543/bed76895b05bc65ac0d92d7e25bcfcc7 to your computer and use it in GitHub Desktop.
Have the function MinWindowSubstring(strArr) take the array of strings stored in strArr, which will contain only two strings, the first parameter being the string N and the second parameter being a string K of some characters, and your goal is to determine the smallest substring of N that contains all the characters in K. For example: if strArr …
// https://coderbyte.com/editor/Min%20Window%20Substring:Kotlin
/**
* Min Window Substring
* Have the function MinWindowSubstring(strArr) take the array of strings stored in strArr, which will contain only two strings, the first parameter being the string N and the second parameter being a string K of some characters, and your goal is to determine the smallest substring of N that contains all the characters in K. For example: if strArr is ["aaabaaddae", "aed"] then the smallest substring of N that contains the characters a, e, and d is "dae" located at the end of the string. So for this example your program should return the string dae.
* </p>
* Another example: if strArr is ["aabdccdbcacd", "aad"] then the smallest substring of N that contains all of the characters in K is "aabd" which is located at the beginning of the string. Both parameters will be strings ranging in length from 1 to 50 characters and all of K's characters will exist somewhere in the string N. Both strings will only contains lowercase alphabetic characters.
* </p>
* Examples
* Input: arrayOf("ahffaksfajeeubsne", "jefaa")
* Output: aksfaje
Input: arrayOf("aaffhkksemckelloe", "fhea")
Output: affhkkse
*/
fun MinWindowSubstring(strArr: Array<String>): String {
val str = strArr[0];
val needle = strArr[1]
//start with the smallest possible substrings, then go up
for (i in needle.length..str.length) {
for (j in 0..str.length - i) {
val mySlice = str.substring(j, j + i)
if (isContained(mySlice, needle)) return mySlice
}
}
return "Not in string";
}
fun isContained(str: String, needle: String): Boolean {
val arr = StringBuilder(str)
for (i in needle.indices) {
val place = arr.indexOfFirst { c -> c == needle[i] }
//println("$place : ${needle[i]}")
if (place == -1) {
return false
} else {
//println(arr)
arr.delete(place, place + 1)
}
}
return true;
}
fun main(args: Array<String>) {
println(MinWindowSubstring(arrayOf("ahffaksfajeeubsne", "jefaa")));
println(isContained("affhkkse", "fhea"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment