题目描述:
找出字符串中第一个只出现一次的字符
输入描述:
输入一个非空字符串
输出描述:
输出第一个只出现一次的字符,如果不存在输出-1
思路一:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext())
{
String str = scanner.nextLine();
if (str == null || str.length() == 0)
System.out.println(-1);
else if (str.length() == 1)
System.out.println(str);
else
{
char res = '#';
for (int i = 0; i <= str.length() - 1; i++)
{
char c = str.charAt(i);
if (i == 0)
{
String sub = str.substring(i + 1);
if (sub.contains(c + ""))
continue;
else
{
res = c;
break;
}
}
else if (i == str.length() - 1)
{
String sub = str.substring(0, i);
if (sub.contains(c + ""))
continue;
else
{
res = c;
break;
}
}
else
{
String sub1 = str.substring(0, i);
String sub2 = str.substring(i + 1);
if (sub1.contains(c + "") || sub2.contains(c + ""))
continue;
else
{
res = c;
break;
}
}
}
if (res == '#')
System.out.println(-1);
else
System.out.println(res);
}
}
}
}
思路二:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext())
{
String str = scanner.nextLine();
if (str == null || str.length() == 0)
System.out.println(-1);
else if (str.length() == 1)
System.out.println(str);
else
{
boolean flag = false;
for (int i = 0; i < str.length(); i++)
{
StringBuffer sb = new StringBuffer(str);
StringBuffer sub = sb.deleteCharAt(i);
if (!sub.toString().contains(str.charAt(i) + ""))
{
System.out.println(str.charAt(i));
flag = true;
break;
}
}
if (flag == false)
System.out.println(-1);
}
}
}
}
思路三:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext())
{
String str = scanner.nextLine();
if (str == null || str.length() == 0)
System.out.println(-1);
else if (str.length() == 1)
System.out.println(str);
else
{
boolean flag = false;
for (char c: str.toCharArray())
{
int index1 = str.indexOf(c);
int index2 = str.lastIndexOf(c);
if (index1 == index2)
{
System.out.println(c);
flag = true;
break;
}
}
if (flag == false)
System.out.println(-1);
}
}
}
}