Java code to find first non repeated character

Problem: 

Write a java program to determine the first non-repeated character in a
string.

Solution: 

  
  public class Main {
  
    public static <T> void println(T s) {
        System.out.println(s);
    }

    public static void main(String[] args) {
        char fnr = firstNonRepeated("this is a string");
        println(fnr);
    }
  
  
    /**
     * First non-repeated character
     */
    public static class Node {
        public char data;
        public Node p;
        public Node n;
    }

    public static char firstNonRepeated(String str) {
        int[] lookup = new int[127];
        Node[] nodes = new Node[127];
        Node head = null;
        Node tail = null;

       
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            lookup[(int) ch] += 1;

            if (head == null) {
                head = new Node();
                head.data = ch;
                tail = head;
                nodes[(int) ch] = head;
                continue;
            }


            int repeat = lookup[(int) ch];
            if (repeat == 2) {
                Node b = nodes[(int) ch];
                // remove
                if (head == tail) {
                    head = null;
                    tail = null;
                } else if (b == head) {
                    head = b.n;
                } else if (b == tail) {
                    tail = b.p;
                } else {
                    Node a = b.p;
                    Node c = b.n;
                    a.n = c;
                    c.p = a;
                }

                nodes[(int) ch] = null;
            } else if (repeat == 1) {
                Node b = tail;
                tail = new Node();
                tail.data = ch;
                tail.p = b;
                b.n = tail;

                nodes[(int) ch] = tail;
            }
        }
        if (head != null) return head.data;
        return (char) -1;
    }
  }
  
Share this Post

Leave a Reply

Your email address will not be published. Required fields are marked *