String || LeetCode || Swift
345. Reverse Vowels of a String
Given a string s
, reverse only all the vowels in the string and return it.
The vowels are 'a'
, 'e'
, 'i'
, 'o'
, and 'u'
, and they can appear in both lower and upper cases, more than once.
func reverseVowels(_ s: String) -> String {
var length = s.count - 1
var index = 0
var vowels = ["a","e","i","o","u"]
var s = Array(s)
while index <= length {
var value = s[index].lowercased()
if(!vowels.contains(String(value))){
index += 1
continue
}
var endvalue = s[length].lowercased()
if(!vowels.contains(String(endvalue))){
length -= 1
continue
}
s.swapAt(index, length)
length -= 1
index += 1
}
return String(s)
}
2515. Shortest Distance to Target String in a Circular Array
ou are given a 0-indexed circular string array words
and a string target
. A circular array means that the array's end connects to the array's beginning.
- Formally, the next element of
words[i]
iswords[(i + 1) % n]
and the previous element ofwords[i]
iswords[(i - 1 + n) % n]
, wheren
is the length ofwords
.
Starting from startIndex
, you can move to either the next word or the previous word with 1
step at a time.
Return the shortest distance needed to reach the string target
. If the string target
does not exist in words
, return -1
.
func closetTarget(_ words: [String], _ target: String, _ startIndex: Int) -> Int {
if(words[startIndex] == target){
return 0
}
var result:Int = Int.max
var index = 0
while index < words.count {
if(words[index] == target) {
result = min(result, abs(index - startIndex), words.count - abs(index - startIndex))
}
index += 1
}
if(result == Int.max){
return -1
}
return result
}
13. Roman to Integer
Roman numerals are represented by seven different symbols: I
, V
, X
, L
, C
, D
and M
.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
func romanToInt(_ s: String) -> Int {
var characters = Array(s)
let mapCharacter:[Character:Int] = ["I":1,"V":5,"X":10,"L":50, "C":100,"D":500,"M":1000]
var firstPointer = 0
var finalPointer = 1
var result = 0
while finalPointer < characters.count{
let firstValue = mapCharacter[characters[firstPointer]] ?? 0
let secondValue = mapCharacter[characters[finalPointer]] ?? 0
if(firstValue >= secondValue){
result = result + firstValue
}else{
result = result - firstValue
}
finalPointer += 1
firstPointer += 1
}
result = result + (mapCharacter[characters[characters.count - 1]] ?? 0)
return result
}
844. Backspace String Compare
Given two strings s
and t
, return true
if they are equal when both are typed into empty text editors. '#'
means a backspace character.
Note that after backspacing an empty text, the text will continue empty.
func backspaceCompare(_ s: String, _ t: String) -> Bool {
return stack(s) == stack(t)
}
private func stack(_ s: String) -> [Character] {
var sStack: [Character] = []
for char in s {
if char == "#" {
if !sStack.isEmpty {
_ = sStack.removeLast()
}
} else {
sStack.append(char)
}
}
return sStack
}
20. Valid Parentheses
Given a string s
containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
- Every close bracket has a corresponding open bracket of the same type.
func isValid(_ s: String) -> Bool {
var stack:[Character] = [Character]()
for ch in s{
switch ch{
case "(": stack.append(")")
case "{": stack.append("}")
case "[" : stack.append("]")
default:
if let lastCharacter = stack.popLast(){
if((lastCharacter) != ch){
return false
}
}else{
return false
}
}
}
return stack.count == 0
}
125. Valid Palindrome
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string s
, return true
if it is a palindrome, or false
otherwise.
func isPalindrome(_ s: String) -> Bool {
let filterdString = s.filter { "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ1234567890".contains($0) }.uppercased()
var i = 0;
var j = filterdString.count - 1;
while( i < j) {
if(filterdString[i] == filterdString[j]) {
i = i + 1
j = j - 1 ;
} else {
return false;
}
}
return true;
}
}
extension StringProtocol {
subscript(offset: Int) -> Character {
self[index(startIndex, offsetBy: offset)]
}
2405. Optimal Partition of String
Given a string s
, partition the string into one or more substrings such that the characters in each substring are unique. That is, no letter appears in a single substring more than once.
Return the minimum number of substrings in such a partition.
Note that each character should belong to exactly one substring in a partition.
func partitionString(_ s: String) -> Int {
var set:Set<Character> = Set<Character>()
var result = 1
for char in s{
if(set.contains(char)){
result += 1
set.removeAll()
}
set.insert(char)
}
return result
}
541. Reverse String II
Given a string s
and an integer k
, reverse the first k
characters for every 2k
characters counting from the start of the string.
If there are fewer than k
characters left, reverse all of them. If there are less than 2k
but greater than or equal to k
characters, then reverse the first k
characters and leave the other as original.
func reverseStr(_ s: String, _ k: Int) -> String {
var word = ""
var result = ""
var index = 0
var tracker = k
var isReverse = true
for (index,char) in s.enumerated(){
if(isReverse){
tracker = tracker - 1
word = String(char) + word
if(tracker == 0){
isReverse = false
}
}else{
tracker = tracker + 1
result = result + word + String(char)
word = ""
if(tracker == k){
isReverse = true
}
}
}
return result + word
}
557. Reverse Words in a String III
Given a string s
, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
func reverseWords(_ s: String) -> String {
var res = ""
var word = ""
for char in s{
if(char == " "){
res += word + String(char)
word = ""
}else{
word = String(char) + word
}
}
return res + word
}
2273. Find Resultant Array After Removing Anagrams
func removeAnagrams(_ words: [String]) -> [String] {
var words = words
var index = 1
while index < words.count{
if(words[index].sorted() == words[index - 1].sorted()){
words.remove(at:index)
}else{
index += 1
}
}
return words
}
71. Simplify Path
Given a string path
, which is an absolute path (starting with a slash '/'
) to a file or directory in a Unix-style file system, convert it to the simplified canonical path.
In a Unix-style file system, a period '.'
refers to the current directory, a double period '..'
refers to the directory up a level, and any multiple consecutive slashes (i.e. '//'
) are treated as a single slash '/'
. For this problem, any other format of periods such as '...'
are treated as file/directory names.
func simplifyPath(_ path: String) -> String {
var pathStack = [String]()
var components = path.split(separator:"/")
for component in components{
switch component {
case "": break
case ".": break
case "..": pathStack.popLast()
default:
pathStack.append(String(component))
}
}
return "/" + String(pathStack.joined(separator:"/"))
}
567. Permutation in String
Given two strings s1
and s2
, return true
if s2
contains a permutation of s1
, or false
otherwise.
In other words, return true
if one of s1
's permutations is the substring of s2
.
func checkInclusion(_ s1: String, _ s2: String) -> Bool {
var s1Map = [Character:Int]()
var s2Map = [Character:Int]()
var s2Array = Array(s2)
for value in s1{
s1Map[value, default:0] += 1
}
for (index, value) in s2.enumerated(){
if(index >= s1.count){
var s2Value = s2Array[index - s1.count ]
var s1Mapvalue = s2Map[s2Value] ?? 0
s2Map[s2Value] = s1Mapvalue > 1 ? s1Mapvalue - 1 : nil
}
s2Map[value, default:0] += 1
if(s1Map == s2Map){
return true
}
}
return false
}
680. Valid Palindrome II
Given a string s
, return true
if the s
can be palindrome after deleting at most one character from it.
func validPalindrome(_ s: String) -> Bool {
var sArr = Array(s)
var index = 0
var sLength = s.count - 1
while index < sLength{
if(sArr[index] != sArr[sLength]){
return checkPalindrome(s, index + 1 , sLength) || checkPalindrome(s, index , sLength - 1)
}
index += 1
sLength -= 1
}
return true
}
func checkPalindrome(_ s:String,_ left:Int,_ right:Int) -> Bool{
var sArr = Array(s)
var left = left
var right = right
while left < right{
if(sArr[left] != sArr[right]){
return false
}
left += 1
right -= 1
}
return true
}
151. Reverse Words in a String
func reverseWords(_ s: String) -> String {
return s.split(separator:" ").reversed().joined(separator: " ")
}
Input: s = "the sky is blue"
Output: "blue is sky the"
500. Keyboard Row
Given an array of strings words
, return the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below.
In the American keyboard:
- the first row consists of the characters
"qwertyuiop"
, - the second row consists of the characters
"asdfghjkl"
, and - the third row consists of the characters
"zxcvbnm"
.
func findWords(_ words: [String]) -> [String] {
let firstRow = Set("qwertyuiop")
let secondRow = Set("asdfghjkl")
let thirdRow = Set("zxcvbnm")
var result = [String]()
for value in words{
let charSet = Set(value.lowercased())
if(charSet.isSubset(of:firstRow) || charSet.isSubset(of:secondRow) || charSet.isSubset(of:thirdRow)){
result.append(value)
}
}
return result
}
2351. First Letter to Appear Twice
func repeatedCharacter(_ s: String) -> Character {
var characterFreq = [Character:Int]()
for val in s{
characterFreq[val, default:0] += 1
if let value = characterFreq[val]{
if(value >= 2){
return val
}
}
}
var character:Character = "a"
return character
}
344. Reverse String
func reverseString(_ s: inout [Character]) {
var index = 0
var length = s.count - 1
while index <= length{
// (s[length], s[index] = s[index], s[length])
var temp = s[length]
s[length] = s[index]
s[index] = temp
index += 1
length -= 1
}
}
1003. Check If Word Is Valid After Substitutions
func isValid(_ s: String) -> Bool {
var index = 0
var s = s
while index < s.count{
if s.range(of:"abc") != nil {
print("exists")
s = s.replacingOccurrences(of: "abc", with: "", options: NSString.CompareOptions.literal, range: nil)
}else{
break
}
}
return s.count == 0
}
1002. Find Common Characters
Given a string array words
, return an array of all characters that show up in all strings within the words
(including duplicates). You may return the answer in any order.
func commonChars(_ words: [String]) -> [String] {
var visited = [Character:Int]()
var words1 = words[0]
for ch in words1{
visited[ch, default:0] += 1
}
for i in 1..<words.count{
var word = words[i]
var localMap = [Character:Int]()
for ch in word{
localMap[ch, default:0] += 1
}
for (key,value) in visited{
if let localKeyFreq = localMap[key]{
if localKeyFreq > 0 {
visited[key] = min(value,localKeyFreq)
}
}else{
visited[key] = nil
}
}
}
var result = [String]()
for (key,value) in visited{
if(value > 0){
var value = Array(repeating:"\(key)" , count:value)
result = result + value
}
}
return result
}
1071. Greatest Common Divisor of Strings
For two strings s
and t
, we say "t
divides s
" if and only if s = t + ... + t
(i.e., t
is concatenated with itself one or more times).
Given two strings str1
and str2
, return the largest string x
such that x
divides both str1
and str2
.
func gcdOfStrings(_ str1: String, _ str2: String) -> String {
if str1 + str2 != str2 + str1{
return ""
}
let str11 = Array(str1)
var gcd = gcd(str1.count, str2.count)
return String(str11[0..<gcd])
}
func gcd(_ a: Int, _ b: Int) -> Int {
let remainder = abs(a) % abs(b)
if remainder != 0 {
return gcd(abs(b), remainder)
} else {
return abs(b)
}
}
8. String to Integer (atoi)
Implement the myAtoi(string s)
function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi
function).
func myAtoi(_ s: String) -> Int {
guard !s.contains("+ ") else { return 0 }
let val = (s as NSString).integerValue
return val >= Int32.max ? Int(Int32.max) : max(Int(Int32.min), val)
}
415. Add Strings
func addStrings(_ num1: String, _ num2: String) -> String {
var s1 = Array(num1)
var s2 = Array(num2)
var s1C = s1.count - 1
var s2C = s2.count - 1
var carry = 0
var result = ""
while s1C >= 0 || s2C >= 0{
var x1 = 0
if (s1C >= 0){
let value = s1[s1C]
x1 = Int(String(value))!
s1C -= 1
}
var x2 = 0
if (s2C >= 0){
x2 = Int(String(s2[s2C]))!
s2C -= 1
}
var sum = x1 + x2 + carry
print("sum",sum)
result = "\(sum%10)" + result
carry = sum / 10
}
if(carry > 0){
result = "\(carry)" + result
}
return result
}
3. Longest Substring Without Repeating Characters
Given a string s
, find the length of the longest substring without repeating characters.
func lengthOfLongestSubstring(_ s: String) -> Int {
var longestString = 0 , startIndex = 0
var charMap = [Character:Int]()
for (index, ch) in s.enumerated(){
if let foundIndex = charMap[ch]{
startIndex = max(foundIndex + 1,startIndex)
}
longestString = max(longestString, index - startIndex + 1)
charMap[ch] = index
}
return longestString
}
443. String Compression
func compress(_ chars: inout [Character]) -> Int {
var index = 0
var indexAns = 0
var length = chars.count
while index < length{
var count = 0
var currentChar = chars[index]
while (index < chars.count && chars[index] == currentChar){
index += 1
count += 1
}
chars[indexAns] = Character("\(currentChar)")
indexAns += 1
if(count != 1){
let stringCount = Array("\(count)")
for val in stringCount{
chars[indexAns] = Character("\(val)")
indexAns += 1
}
}
}
return indexAns
}
Input: chars = ["a","a","b","b","c","c","c"]
Output: Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]
Explanation: The groups are "aa", "bb", and "ccc". This compresses to "a2b2c3".
Example 2:
Input: chars = ["a"]
Output: Return 1, and the first character of the input array should be: ["a"]
Explanation: The only group is "a", which remains uncompressed since it's a single character.
58. Length of Last Word
func lengthOfLastWord(_ s: String) -> Int {
var index = 0
var end = s.count - 1
var s = Array(s)
var startScanning = false
var count = 0
while index <= end{
if(s[end] == " "){
if(startScanning){
break
}
}else{
startScanning = true
count += 1
}
end = end - 1
}
return count
}
Example 1:
Input: s = "Hello World"
Output: 5
Explanation: The last word is "World" with length 5.
Example 2:
Input: s = " fly me to the moon "
Output: 4
Explanation: The last word is "moon" with length 4.
1209. Remove All Adjacent Duplicates in String II
func removeDuplicates(_ s: String, _ k: Int) -> String {
var stack = [(char: Character, count: Int)]()
for char in s {
if !stack.isEmpty && char == stack.last!.char {
if stack.last!.count + 1 == k {
for j in 1...k-1 {
stack.popLast()
}
} else {
stack.append((char, stack.last!.count + 1))
}
} else {
stack.append((char, 1))
}
}
return stack.map{String($0.char)}.joined(separator: "")
}
Example 1:
Input: s = "abcd", k = 2
Output: "abcd"
Explanation: There's nothing to delete.
Example 2:
Input: s = "deeedbbcccbdaa", k = 3
Output: "aa"
Explanation:
First delete "eee" and "ccc", get "ddbbbdaa"
Then delete "bbb", get "dddaa"
Finally delete "ddd", get "aa"
1047. Remove All Adjacent Duplicates In String
func removeDuplicates(_ s: String) -> String {
var result = [Character]()
for ch in s{
if(result.count == 0){
result.append(ch)
}else{
var lastElement = result[result.count - 1]
if(lastElement == ch){
result.removeLast()
}else{
result.append(ch)
}
}
}
return String(result)
}
Input: s = "abbaca"
Output: "ca"
Explanation:
For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca".
2390. Removing Stars From a String
You are given a string s
, which contains stars *
.
In one operation, you can:
- Choose a star in
s
. - Remove the closest non-star character to its left, as well as remove the star itself.
Return the string after all stars have been removed.
Note:
- The input will be generated such that the operation is always possible.
- It can be shown that the resulting string will always be unique.
func removeStars(_ s: String) -> String {
var result = ""
for ch in s{
if(ch == "*"){
result.removeLast()
}else{
result = result + "\(ch)"
}
}
return result
}
14. Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string ""
.
func longestCommonPrefix(_ strs: [String]) -> String {
if(strs.count == 0){
return ""
}
var commonPrefix = strs[0]
for str in strs[1..<strs.count]{
while !str.hasPrefix(commonPrefix){
commonPrefix = String(commonPrefix.dropLast())
}
}
return commonPrefix
}
242. Valid Anagram
func isAnagram(_ s: String, _ t: String) -> Bool {
var sMap = [Character:Int]()
var tMap = [Character:Int]()
for value in s {
sMap[value, default:0] += 1
}
for value in t {
tMap[value, default:0] += 1
}
return sMap == tMap
}
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: false
387. First Unique Character in a String
Given a string s
, find the first non-repeating character in it and return its index. If it does not exist, return -1
.
func firstUniqChar(_ s: String) -> Int {
var uniqueMap:[Character:Int] = [Character:Int]()
var endLength = s.count
var s = Array(s)
var index = 0
while index < endLength{
if let value = uniqueMap[s[index]]{
uniqueMap[s[index]] = value + 1
}else{
uniqueMap[s[index]] = 1
}
index += 1
}
index = 0
endLength = s.count
while index < endLength{
if let value = uniqueMap[s[index]]{
if(value <= 1){
return index
}
}
index += 1
}
return -1
}
394. Decode String*
func decodeString(_ s: String) -> String {
var num = 0
var map:[(String,Int)] = []
var str = ""
for c in s{
switch c{
case "[":
map.append((str, num))
num = 0
str = ""
case "]":
let (ps,n) = map.removeLast()
str = ps + String(repeating:str,count:n)
default:
if c.isLetter{
str.append(c)
}else{
num = num * 10 + c.wholeNumberValue!
}
}
}
return str
}
Example 1:
Input: s = "3[a]2[bc]"
Output: "aaabcbc"
Example 2:
Input: s = "3[a2[c]]"
Output: "accaccacc"
Example 3:
Input: s = "2[abc]3[cd]ef"
Output: "abcabccdcdcdef"
451. Sort Characters By Frequency
func frequencySort(_ s: String) -> String {
var freqByChar: [Character: Int] = [:]
for char in s {
freqByChar[char, default: 0] += 1
}
var sortedArrayOfFreq = freqByChar
.map { ($0, $1) }
.sorted(by: { $0.1 > $1.1 })
var result: [Character] = []
for (char, freq) in sortedArrayOfFreq {
let chars: [Character] = .init(repeating: char, count: freq)
result += chars
}
return String(result)
}
Input: s = "tree"
Output: "eert"
Explanation: 'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.
Example 2:
Input: s = "cccaaa"
Output: "aaaccc"
Explanation: Both 'c' and 'a' appear three times, so both "cccaaa" and "aaaccc" are valid answers.
Note that "cacaca" is incorrect, as the same characters must be together.
1880. Check if Word Equals Summation of Two Words
func isSumEqual(_ firstWord: String, _ secondWord: String, _ targetWord: String) -> Bool {
var firstNumber = ""
var secondNumber = ""
var thirdNumber = ""
firstWord.map({
firstNumber += String($0.asciiValue! - 97)
})
secondWord.map({
secondNumber += String($0.asciiValue! - 97)
})
targetWord.map({
thirdNumber += String($0.asciiValue! - 97)
})
let firstInt = Int(firstNumber)!
let secondInt = Int(secondNumber)!
let targerInt = Int(thirdNumber)!
return firstInt + secondInt == targerInt
}
Example 1:
Input: firstWord = "acb", secondWord = "cba", targetWord = "cdb"
Output: true
Explanation:
The numerical value of firstWord is "acb" -> "021" -> 21.
The numerical value of secondWord is "cba" -> "210" -> 210.
The numerical value of targetWord is "cdb" -> "231" -> 231.
We return true because 21 + 210 == 231.
Example 2:
Input: firstWord = "aaa", secondWord = "a", targetWord = "aab"
Output: false
Explanation:
The numerical value of firstWord is "aaa" -> "000" -> 0.
The numerical value of secondWord is "a" -> "0" -> 0.
The numerical value of targetWord is "aab" -> "001" -> 1.
We return false because 0 + 0 != 1.
22. Generate Parentheses
Given n
pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
func generateParenthesis(_ n: Int) -> [String] {
var openCloseArray = [Character]()
var openCloseArrayResult = [String]()
openCloseParanthesis(0, 0, n, &openCloseArray, &openCloseArrayResult)
return openCloseArrayResult
}
func openCloseParanthesis(_ openN:Int , _ closeN:Int ,_ numberOfOpenPatanthese:Int ,
_ arr:inout [Character] ,_ result: inout [String]){
if (openN == closeN && openN == numberOfOpenPatanthese){
var value = String(arr)
result.append(value)
}
if(openN < numberOfOpenPatanthese){
arr.append("(")
openCloseParanthesis(openN + 1, closeN, numberOfOpenPatanthese, &arr, &result)
arr.removeLast()
}
if(closeN < openN){
arr.append(")")
openCloseParanthesis(openN, closeN + 1, numberOfOpenPatanthese, &arr, &result)
arr.removeLast()
}
}
Example 1:
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2:
Input: n = 1
Output: ["()"]
49. Group Anagrams
func groupAnagrams(_ strs: [String]) -> [[String]] {
var mapStr = [String:[String]]()
for str in strs{
var sortedArray = String(Array(str).sorted())
if let value = mapStr[sortedArray]{
var value = value
value.append(str)
mapStr[sortedArray] = value
}else{
mapStr[sortedArray] = [str]
}
}
return mapStr.map({$1})
}
2696. Minimum String Length After Removing Substrings
You are given a string s
consisting only of uppercase English letters.
You can apply some operations to this string where, in one operation, you can remove any occurrence of one of the substrings "AB"
or "CD"
from s
.
Return the minimum possible length of the resulting string that you can obtain.
Note that the string concatenates after removing the substring and could produce new "AB"
or "CD"
substrings.
func minLength(_ s: String) -> Int {
var stack = [Character]()
let arr = Array(s)
for c in arr {
if !stack.isEmpty {
let top = stack.last!
if (top == "A" && c == "B") || (top == "C" && c == "D") {
_ = stack.removeLast()
} else {
stack.append(c)
}
} else {
stack.append(c)
}
}
return stack.count
}
1910. Remove All Occurrences of a Substring
func removeOccurrences(_ s: String, _ part: String) -> String {
var string = s
while let range = string.range(of: part) {
string.removeSubrange(range)
}
return string
}
179. Largest Number
func largestNumber(_ nums: [Int]) -> String {
let strings = nums.map { String($0) }.sorted { $0 + $1 > $1 + $0 }
return Int(strings.joined()) == 0 ? "0" : strings.joined()
}
Example 1:
Input: nums = [10,2]
Output: "210"
Example 2:
Input: nums = [3,30,34,5,9]
Output: "9534330"
208. Implement Trie (Prefix Tree)
class Trie {
class Node {
var sentinel = false
var children = [Character:Node]()
}
var root = Node()
init() {
}
func insert(_ word: String) {
var node = root
for ch in word {
node.children[ch] = node.children[ch] ?? Node()
node = node.children[ch]!
}
node.sentinel = true
}
func search(_ word: String) -> Bool {
lookup(word).sentinel
}
func startsWith(_ prefix: String) -> Bool {
lookup(prefix) !== root
}
private func lookup(_ word: String) -> Node {
var node = root
for ch in word {
guard let next = node.children[ch] else { return root }
node = next
}
return node
}
}
647. Palindromic Substrings
Given a string s
, return the number of palindromic substrings in it.
A string is a palindrome when it reads the same backward as forward.
A substring is a contiguous sequence of characters within the string.
func countSubstrings(_ s: String) -> Int {
let s = Array(s)
var res = 0
for (i, ch) in s.enumerated() {
res += palindrom(s, i, i) + palindrom(s, i, i+1)
}
return res
}
func palindrom(_ s: [Character], _ start: Int, _ end: Int) -> Int {
var result = 0, start = start, end = end
while start >= 0 && end < s.count {
guard s[start] == s[end] else { return result }
result += 1; start -= 1; end += 1
}
return result
}
1963. Minimum Number of Swaps to Make the String Balanced
func minSwaps(_ s: String) -> Int {
let arr = Array(s)
var result = 0
var count = 0
for ch in arr {
if ch == "]" {
count += 1
} else {
count -= 1
}
result = max(result, count)
}
return (result + 1) / 2
}
1249. Minimum Remove to Make Valid Parentheses
func minRemoveToMakeValid(_ s: String) -> String {
var s = s.map({String($0)}), stack = [Int]()
print(s)
for i in 0..<s.count {
if s[i] == "(" {
stack.append(i)
} else if s[i] == ")" && stack.popLast() == nil {
s[i] = ""
}
}
for i in stack {
s[i] = ""
}
print(s.joined())
return s.joined()
}