-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
140 lines (112 loc) · 2.29 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
package main
import (
"bytes"
"fmt"
"strconv"
"strings"
)
func comma(s string) string {
n := len(s)
if n <= 3 {
return s
}
return comma(s[:n-3]) + "," + s[n-3:]
}
func intsToString(values []int) string {
var buf bytes.Buffer
buf.WriteByte('[')
for i, v := range values {
if i > 0 {
buf.WriteString(", ")
}
fmt.Fprintf(&buf, "%d", v)
}
buf.WriteByte(']')
return buf.String()
}
func main() {
fmt.Println(intsToString([]int{1, 2, 3})) // "[1, 2, 3]"
}
//SOLUTION 3.10 : INSERT COMMAS INTO BYTE
func insertCommas(str string) string {
x := &bytes.Buffer{}
prev := len(str) % 3
if prev == 0 {
prev = 3
}
x.WriteString(str[:prev])
for i := prev; i < len(str); i += 3 {
x.WriteByte(',')
x.WriteString(str[i : i+3])
}
return x.String()
}
func basename(s string) string {
slash := strings.LastIndex(s, "/") // -1 if "/" not found
s = s[slash+1:]
if dot := strings.LastIndex(s, "."); dot >= 0 {
s = s[:dot]
}
return s
}
func basename2(s string) string {
// Discard last '/' and everything before.
for i := len(s) - 1; i >= 0; i-- {
if s[i] == '/' {
s = s[i+1:]
break
}
}
// Preserve everything before last '.'.
for i := len(s) - 1; i >= 0; i-- {
if s[i] == '.' {
s = s[:i]
break
}
}
return s
}
//3.11 SOLUTION: String format
func Format(n int64) string {
in := strconv.FormatInt(n, 10)
numOfDigits := len(in)
if n < 0 {
numOfDigits-- // First character is the - sign (not a digit)
}
numOfCommas := (numOfDigits - 1) / 3
out := make([]byte, len(in)+numOfCommas)
if n < 0 {
in, out[0] = in[1:], '-'
}
for i, j, k := len(in)-1, len(out)-1, 0; ; i, j = i-1, j-1 {
out[j] = in[i]
if i == 0 {
return string(out)
}
if k++; k == 3 {
j, k = j-1, 0
out[j] = ','
}
}
}
//SOLUTION 3.12 and 3.13 : is Anagram or not
func isAnagram(s string, t string) bool {
lenS := len(s)
lenT := len(t)
if lenS != lenT {
return false
}
anagramMap := make(map[string]int)
for i := 0; i < lenS; i++ {
anagramMap[string(s[i])]++
}
for i := 0; i < lenT; i++ {
anagramMap[string(t[i])]--
}
for i := 0; i < lenS; i++ {
if anagramMap[string(s[i])] != 0 {
return false
}
}
return true
}