-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
99 lines (84 loc) · 1.41 KB
/
main.go
File metadata and controls
99 lines (84 loc) · 1.41 KB
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
package main
import "fmt"
/*
*
*
* find longest common prefix
*
* args :
* nums slices []string
*
* return value:
* string
*
*
*/
func longestCommonPrefix(strs []string) string {
// if length strs in 0 zero
// return empty string
if len(strs) == 0 {
return ""
}
// this for find word
// common prefix
var flag bool = true
// response string
var res string = ""
// loop to first value
// in slice and check
// char <i> in prefix
// other words or not
for i := range strs[0] {
// get one char form
// firs word in strs
// and get char <i>
key := strs[0][i]
// loop to all strs
for _, v := range strs {
// if length one word in strs
// equal zero return empty string
if len(v) == 0 {
return ""
}
// if length one less i
// flag false
// and break loop
// and in down
// return res
if i > len(v)-1 {
flag = false
break
}
// if find one word equal
// key flag true and continue
if key == v[i] {
flag = true
continue
}
// if not flag false
// and break words loop
flag = false
break
}
// if flag is true
// append key
if flag {
res += string(key)
flag = false
// else return res
} else {
return res
}
}
// if all words like
// first word
// exit loop and
// return res
return res
}
func main() {
// very simple test
fmt.Println(longestCommonPrefix(
[]string{"flower", "flow", "flight"},
))
}