java implements the first character detail in the output string that does not repeat
- 2020-07-21 08:13:14
- OfStack
java implements a non-repeating character detail for the first character in the output string
For example: input name output n, input teeter output r, input namename output null
The specific implementation code is as follows:
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String str = in.next();
for(int i =0 ; i < str.length() ; i++)
{
if(str.lastIndexOf(str.char(i)) == i &&
str.indexOf(str.char(i)) == i)
{
System.out.println(str.char(i));
break;
}
}
}
}
In this implementation code we use three method members of the String class:
String. length() : Gets the length of the string
String. charAt(int index) : Gets the characters that index index
String. lastIndexOf(char c) : Gets the index of the last occurrence of the character c in a string
String.indexOf(char c) : Gets the index of the character c the first time it appears in a string
We could have implemented these methods without using strings. Here is the code I personally implemented using for loops:
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String str = in.next();
char[] cb = new char[str.length()];
// Put a character in a string 1 Time deposit cb[]
for(int i =0 ;i <str.length() ; i++)
{
cb[i] = str.charAt(i);
}
for(int i = 0 ; i < str.length() ; i++)
{
for(int j = 0 ; j < str.length() ; j++)
{
if(cb[i] == cb[j] && cb[i] != '0')
{
char c = cb[i];
for(int z = 0 ; z < str.length() ; z++)
{
if(cb[z] == c)
cb[z] = '0';
}
}
}
}
for(int i = 0 ; i <str.length() ; i++)
{
if(cb[i] != '0')
{
System.out.println(cb[i]);
break;
}
}
}
}
This approach can be implemented, but it is extremely time-consuming and overhead, so it is best not to use loop nesting, which is costly to the system unless you have to.
Thank you for reading, I hope to help you, thank you for your support to this site!