Last active
January 22, 2021 06:18
-
-
Save mumunuu/7e196b867c11d6fcdc52a829e08a59ea to your computer and use it in GitHub Desktop.
algorithm(leetcode) First Unique Character in a String
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func firstUniqChar(s string) int { | |
tmpArr := strings.Split(s, "") | |
pastArr := make([]string, 0) | |
for i := 0; i < len(tmpArr); i++ { | |
curVal := tmpArr[i] | |
//이미 했던 값이면 확인하지 말자. | |
if findIndex(pastArr, curVal) != -1 { | |
continue | |
} | |
pastArr = append(pastArr, curVal) | |
duplicateFlag := false | |
for k := i + 1; k < len(tmpArr); k++ { | |
if curVal == tmpArr[k] { | |
duplicateFlag = true | |
break | |
} | |
} | |
if !duplicateFlag { | |
return i | |
} | |
} | |
return -1 | |
} | |
func findIndex(arr []string, key string) int { | |
for i, v := range arr { | |
if key == v { | |
return i | |
} | |
} | |
return -1 | |
} | |
//strings package에 있는 Index와 LastIndex를 통해 비교해도 됨 | |
func firstUniqChar(s string) int { | |
tmpArr := strings.Split(s, "") | |
for i := 0; i < len(tmpArr); i++ { | |
if strings.Index(s, tmpArr[i]) == strings.LastIndex(s, tmpArr[i]) { | |
return i | |
} | |
} | |
return -1 | |
} | |
//golang strings에는 문자열 갯수를 찾아주는 함수가 존재. | |
func firstUniqChar(s string) int { | |
tmpArr := strings.Split(s, "") | |
for i := 0; i < len(tmpArr); i++ { | |
count := strings.Count(s, tmpArr[i]) | |
if count == 1 { | |
return i | |
} | |
} | |
return -1 | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment