Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit6a44164

Browse files
Merge pull requestneetcode-gh#48 from boudhayan/main
Add longest consecutive sequence solution in Swift
2 parentsb1f5578 +ce77879 commit6a44164

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

‎swift/Encode-Decode-Strings.swift‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
2+
classCodec{
3+
func encode(_ strs:[String])->String{
4+
if strs.isEmpty{return"#"}
5+
varcounts=[String]()
6+
forstrin strs{
7+
counts.append("\(str.count)")
8+
}
9+
return counts.joined(separator:",")+"#"+ strs.joined()
10+
}
11+
12+
func decode(_ s:String)->[String]{
13+
if s=="#"{return[]}
14+
letindex= s.firstIndex(of:"#")!
15+
letcounts=String(s[s.startIndex...s.index(before: index)]).components(separatedBy:",")
16+
varsIndex= s.index(after: index)
17+
vardecodedStrings=[String]()
18+
forcountin counts{
19+
letendIndex= s.index(sIndex, offsetBy:Int(count)!-1)
20+
if sIndex> endIndex{
21+
decodedStrings.append("")
22+
continue
23+
}
24+
decodedStrings.append(String(s[sIndex...endIndex]))
25+
sIndex= s.index(after: endIndex)
26+
}
27+
return decodedStrings
28+
29+
}
30+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
classSolution{
2+
func longestConsecutive(_ nums:[Int])->Int{
3+
// remove duplicates numbers
4+
letnumSet=Set(nums)
5+
varlongestSequenceCount=0
6+
// iterate through each number in the numSet
7+
// find the lowest number for a sequence, if num - 1 is not there in the numSet, it means num - 1 is the
8+
// lowest for that particular sequence
9+
fornumin numSetwhere !numSet.contains(num-1){
10+
// num is lowest number for the probable longest consecutive sequence
11+
varvisitingNum= num+1
12+
varcurrentSequenceCount=1
13+
// check if next number exists in the numSet, if so then increase the count
14+
while numSet.contains(visitingNum){
15+
currentSequenceCount+=1
16+
visitingNum+=1
17+
}
18+
// set the maximum count
19+
longestSequenceCount=max(longestSequenceCount, currentSequenceCount)
20+
}
21+
return longestSequenceCount
22+
}
23+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp