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

Commit 60b4382

Browse files
author
Shuo
authored
Merge pull request #426 from openset/develop
Add: Find Common Characters
2 parents 6e58cb3 + a6b0ac4 commit 60b4382

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package find_common_characters
2+
3+
func commonChars(A []string) []string {
4+
ans, m, l := make([]string, 0), make([][26]int, len(A)), len(A)
5+
for i, str := range A {
6+
for _, c := range str {
7+
m[i][c-'a']++
8+
}
9+
}
10+
for i, c := range m[0] {
11+
for c > 0 {
12+
c--
13+
for j := 1; j < l; j++ {
14+
if m[j][i] > 0 {
15+
m[j][i]--
16+
} else {
17+
c = -1
18+
break
19+
}
20+
}
21+
if c >= 0 {
22+
ans = append(ans, string(i+'a'))
23+
}
24+
}
25+
}
26+
return ans
27+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package find_common_characters
2+
3+
import (
4+
"reflect"
5+
"testing"
6+
)
7+
8+
type caseType struct {
9+
input []string
10+
expected []string
11+
}
12+
13+
func TestCommonChars(t *testing.T) {
14+
tests := [...]caseType{
15+
{
16+
input: []string{"bella", "label", "roller"},
17+
expected: []string{"e", "l", "l"},
18+
},
19+
{
20+
input: []string{"cool", "lock", "cook"},
21+
expected: []string{"c", "o"},
22+
},
23+
}
24+
for _, tc := range tests {
25+
output := commonChars(tc.input)
26+
if !reflect.DeepEqual(output, tc.expected) {
27+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
28+
}
29+
}
30+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /