First non-repeating character using one traversal of string | Set 2

 import java.util.*;

import java.io.*;

import java.lang.*;



public class HelloWorld{

    

    static int firstnonrepeat(String str){

        

        int no_of_char = 256;

        

        int arr[] = new int[no_of_char];

        for(int i = 0;i<no_of_char;i++){

            arr[i] = -1;  //every time any no come it is -1

        }

        

        for(int j = 0;j<str.length();j++){

            

            if(arr[str.charAt(j)]==-1){

                arr[str.charAt(j)] = j;

            }else{

                arr[str.charAt(j)] = -2;

            }

        }

        

        int res = Integer.MAX_VALUE;

        for(int i = 0; i<no_of_char;i++){

            

            if(arr[i] >= 0){

                res = Math.min(res,arr[i]);

            }

        }

        

        return res;

    }


     public static void main(String []args){

        String str = "geeksforgeeks";

        int index = firstnonrepeat(str);

        if(index == Integer.MAX_VALUE){

            System.out.print("all character are repetaed or empty");

        }else{

            System.out.print("non repetated character is "+ str.charAt(index));

        }

     }

}

Comments

Popular posts from this blog

Git and Github

Testing 08/02/2022