Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Subramanya Chakravarthy
Subramanya Chakravarthy

Posted on

     

First Unique Character in a String

For a given string, what's the best way to figure out first unique character in a string

  1. Create a object or map that holds the count of characters in a string
  2. Loop through the string and update the charObj
  3. Loop through the string again and check charObj and return the index when a character count is 1
  4. If there is no unique character at the end return -1

here's the code

let charMap = new Map()for(let i = 0; i < s.length; i++) {    if(charMap.has(s[i])) {        charMap.set(s[i], charMap.get(s[i]) + 1)    } else {        charMap.set(s[i], 1)    }}for(let i = 0; i < s.length; i++) {    if(charMap.get(s[i]) == 1) {        return i    }}return -1

Thanks for reading 😍

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

  • Location
    Bangalore
  • Education
    Self Taught Developer
  • Joined

Trending onDEV CommunityHot

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp