0% found this document useful (0 votes)
19 views

Java Program

This Java program finds the first repeated character in a string using a O(N^2) nested loop algorithm. It takes a string as input, has two for loops to compare each character to every other character, returns the index of the first match, or -1 if not found. It tests the method on the string "geeksforgeeks" and prints the index or "Not found" message.

Uploaded by

Er Shweta Tyagi
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Java Program

This Java program finds the first repeated character in a string using a O(N^2) nested loop algorithm. It takes a string as input, has two for loops to compare each character to every other character, returns the index of the first match, or -1 if not found. It tests the method on the string "geeksforgeeks" and prints the index or "Not found" message.

Uploaded by

Er Shweta Tyagi
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 4

// Java program to find the fist character

// that is repeated

import java.io.*;

import java.util.*;

class GFG {

static int findRepeatFirstN2(String s)

// this is O(N^2) method

int p = -1, i, j;

for (i = 0; i < s.length(); i++)


{

for (j = i + 1; j < s.length(); j++)

if (s.charAt(i) == s.charAt(j))

p = i;

break;

if (p != -1)

break;

}
return p;

// Driver code

static public void main (String[] args)

String str = "geeksforgeeks";

int pos = findRepeatFirstN2(str);

if (pos == -1)

System.out.println("Not found");

else
System.out.println( str.charAt(pos));

You might also like