Java easy solution O(N)---use switch


  • 0
    H

    public class Solution {
    public int switchNumber(char letter) {
    switch (letter) {
    case 'a':
    return 0;
    case 'b':
    return 1;
    case 'c':
    return 2;
    case 'd':
    return 3;
    case 'e':
    return 4;
    case 'f':
    return 5;
    case 'g':
    return 6;
    case 'h':
    return 7;
    case 'i':
    return 8;
    case 'j':
    return 9;
    case 'k':
    return 10;
    case 'l':
    return 11;
    case 'm':
    return 12;
    case 'n':
    return 13;
    case 'o':
    return 14;
    case 'p':
    return 15;
    case 'q':
    return 16;
    case 'r':
    return 17;
    case 's':
    return 18;
    case 't':
    return 19;
    case 'u':
    return 20;
    case 'v':
    return 21;
    case 'w':
    return 22;
    case 'x':
    return 23;
    case 'y':
    return 24;
    case 'z':
    return 25;
    default:
    return 26;
    }
    }
    public int firstUniqChar(String s) {
    char str[] = s.toCharArray();
    int num[] = new int[26];
    for (int i = 0; i < s.length(); i++) {
    num[switchNumber(s.charAt(i))] += 1;
    }
    for(int j=0;j<s.length();j++){
    if(num[switchNumber(s.charAt(j))]==1){
    return j;
    }
    }

        return -1;
    }
    

    }


  • 0
    N

    I don't think it's correct and you don't need a switch, but only subtracting 'a' from the character.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.