首页 > 试题广场 >

找出字符串中第一个只出现一次的字符

[编程题]找出字符串中第一个只出现一次的字符
  • 热度指数:199093 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
找出字符串中第一个只出现一次的字符


数据范围:输入的字符串长度满足



输入描述:

输入一个非空字符串



输出描述:

输出第一个只出现一次的字符,如果不存在输出-1

示例1

输入

asdfasdfo

输出

o
package HUAWEI2;

import java.util.Scanner;

/**
 * 找出字符串中第一个只出现一次的字符
 * @author Administrator
 *
 */
public class Demo19 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while(sc.hasNext()){
			String s = sc.next();
			boolean flag = true;
			for(int i=0;i<s.length();i++){
				Character temp = s.charAt(i);
				if(s.lastIndexOf(temp.toString())==s.indexOf(temp.toString())&&flag){
					System.out.println(temp.toString());
					flag = false;
				}
			}
			if(flag){
				System.out.println(-1);
			}

		}
		sc.close();
	}
}


发表于 2016-12-14 20:50:33 回复(1)
用哈希统计词频
#include<iostream>
#include<string>
using namespace std;
const int tableSize = 256;
int hasTable[tableSize];
int main(){
    string s;
    while(cin>>s){
        bool flag = false;
        for(int i=0;i<tableSize;++i) hasTable[i]=0;
        for(int i=0;i<s.size();++i) hasTable[s[i]]++;
        for(int i=0;!flag && i<s.size();++i){
            if(hasTable[s[i]] == 1){
                cout<<s[i]<<endl;
                flag = true;
                break;
            }
        }
        if(!flag)
            cout<<'.'<<endl;
    }
    return 0;
}
编辑于 2016-08-27 10:18:20 回复(2)
import java.util.Scanner;

public class OneTimesChar {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		while(scanner.hasNext()){
			String line = scanner.nextLine();
			System.out.println(getOneTimeChar(line));
		}
		scanner.close();
	}
	
	public static char getOneTimeChar(String line){
		int index = -1;
		char[] ch = line.toCharArray();
		int[] count = new int[ch.length];
		for(int i=0;i<ch.length;i++){
			count[i]=1;
		}
		for(int i=0;i<ch.length;i++){
			for(int j=i+1;j<ch.length;j++){
				if(ch[i]==ch[j]){
					count[i]++;
					count[j]++;
					continue;
				}
			}
		}
		for(int i=0;i<count.length;i++){
			if(count[i]==1){
				index = i;
				break;
			}
		}
		return ch[index];
	}
}
发表于 2016-08-10 15:08:45 回复(1)
#include <iostream>
#include <string>

using namespace std;

//开辟两个数组用来存字符出现的次数alpha和出现的时间点times.
//遍历字符串之后, 再同时遍历alpha和times, 找出alpha[i]==1 && times[i]最小的那个i即可
int alpha[58] = {0};
int times[58] = {0};
int main()
{
    string s;
    char res;
    int min;
    while(cin >> s) {
        res = '#';
        min = s.size()+1;
        for(int i=0; i<s.size(); i++) {
            alpha[s[i] - 'A'] ++;
            times[s[i] - 'A'] = i;
        }
        for(int i=0; i<s.size(); i++) {
            if(alpha[s[i]-'A']==1 && times[s[i]-'A']<min) {
                res = s[i];
                min = times[s[i]-'A'];
            }
        }
        if('#' == res)
            cout << "no" << endl;
        else
            cout << res << endl;
        for(int i=0; i<58; i++) {
            alpha[i]=0;
            times[i]=0;
        }

    }
}

发表于 2016-08-09 10:22:43 回复(0)
a = input()
flag =''
for i in a:
    if a.count(i)==1:
        flag = i
        break
    else:
        flag = -1
print(flag)

发表于 2022-07-02 23:37:07 回复(0)
while True:
    try:
        s = input()
        dc = {}
        for i in s:
            n = s.count(i)
            dc[i] = n
        for m, n in dc.items():
            if n == 1:
                print(m)
                break
        else:
            print(-1)

    except:
        break

发表于 2022-04-01 20:57:39 回复(0)
import java.util.*;
public class Main {
    public static void main(String[] args) {
                //利用数组模拟hashmap
        Scanner in = new Scanner(System.in);
        while (in.hasNextLine()) {
            String str = in.nextLine();
            int[] count = new int[26];
            int flag = 0;
            for (int i = 0; i < str.length(); ++i) {
                count[str.charAt(i) - 'a']++;
            }
            for (int i = 0; i < str.length(); ++i) {
                if (count[str.charAt(i) - 'a'] == 1) {
                    System.out.println(str.charAt(i));
                    break;
                } else flag++;
            }
            if (flag == str.length()) {
                System.out.println(-1);
            }
        }
    }
}


发表于 2022-01-12 19:47:19 回复(0)
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);

     while(in.hasNextLine()){
         Map<Character,Integer>map=new HashMap<>();
         String s=in.nextLine();
         for(char c:s.toCharArray()){
             map.put(c,map.getOrDefault(c,0)+1);
         }
         boolean success=false;
         for(char c:s.toCharArray()){
             if(map.get(c)==1) {
                 System.out.println(c);
                 success=true;
                 break;
             }
         }
         if(!success) System.out.println("-1");
     }
    }
}
发表于 2022-01-11 13:40:34 回复(0)
灵活应用for ....else
while True:
    try:
        s = input()
        b = ""
        for i in s:
            if i not in b:
                b += i
        for j in b:
            if s.count(j)==1:
                print(j)
                break
        else:
            print(-1)
    except:
        break


发表于 2022-01-07 14:04:09 回复(0)
while True:
    try:
        str1=input()
        l=list(str1)
        ln=[]
        for i in l:
            if l.count(i)==1:
                print(i)
                ln.append(i)
                break
        if len(ln)==0:
            print(-1)
    except:
        break

发表于 2021-12-02 16:53:34 回复(0)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String s;
        while ((s = br.readLine()) != null) {
            HashMap<Character, Integer> map = new LinkedHashMap();
            boolean flag = true;
            for (int i = 0; i < s.length(); i++) {
                map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0) + 1);
            }
            for (Map.Entry<Character, Integer> entry : map.entrySet()) {
                if (entry.getValue() == 1) {
                    System.out.println(entry.getKey());
                    flag = false;
                    break;
                }
            }
            if (flag) System.out.println(-1);
        }
    }
}

发表于 2021-09-27 08:55:25 回复(0)
#include <iostream>
#include <string>
#include <map>
using namespace std;

int main(){
    string s;
    while(cin >> s){
        map<char, int> m;
        for(auto i : s)
            m[i]++;
        for(int i = 0; i < s.size(); ++i){
            if(m[s[i]] == 1){
                cout << s[i] << endl;
                break;
            }
            if(i == s.size() - 1 && m[i] !=  1)
                cout << -1 << endl;
        }
    }
    return 0;
}

发表于 2021-08-07 10:36:03 回复(2)
while True:
    try:
        n = input()
        re={}
        cnt=0
        for i in n:
            if i not in re:
                re[i] =1
            else:
                re[i] +=1
        for key, value in re.items():
            if value == 1 and cnt==0:
                print(key)
                cnt=1
        if  value != 1 and cnt==0:
            print(-1)
    except:
        break

发表于 2021-08-05 17:49:10 回复(0)
#include<iostream>
#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<string.h>
#include<vector>
using namespace std;
int main()
{
    string s;
    while(cin>>s) {
        int fre[300];
        memset(fre,0,sizeof(fre));
        for(char ch:s) {
            fre[ch]++;
        }
        bool flag=false;
        for(char ch:s) {
            if(fre[ch]==1) {
                cout<<ch<<endl;
                flag=true;
                break;
            }
        }
        if(!flag)
            cout<<-1<<endl;
    }
    return 0;
}

发表于 2021-06-28 14:23:10 回复(0)

Python的两种解法

第一种用字典,统计好每个字符的个数之后,从字典里按顺序找到个数为1的字符输出就可以了。
用字典处理的方法可以用的题目相对而言广泛一点,可以用来处理更复杂一点的问题。

while True:
    try:
        s = list(input())
        dic = {}
        char = -1
        for i in range(len(s)):
            if s[i] in dic:
                dic[s[i]] += 1
            else:
                dic[s[i]] = 1
        for i in dic:
            if dic[i] == 1:
                char = i
                break
        print(char)
    except EOFError:
        break

就这道题目而言,下面这种不用字典,直接count的方法更简单

while True:
    try:
        s = list(input())
        char = -1
        for i in s:
            if s.count(i) == 1:
                char = i 
                break
        print(char)
    except EOFError:
        break
发表于 2021-04-12 15:42:56 回复(0)
import java.util.*;

public class Main{
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()){
            Boolean found = false;
            List<String> input = new ArrayList<>(Arrays.asList(scanner.next().split("")));
            for (String s : input){
                if (Collections.frequency(input,s) == 1){
                    System.out.println(s);
                    found = true;
                    break;
                }
            }
            if (!found){
                System.out.println("-1");
            }
        }
    }
}

发表于 2021-01-19 00:25:28 回复(0)
#include <bits/stdc++.h>
using namespace std;
int main(){
    string a;
    while(cin>>a){
        int len=a.size();
        bool flag=true;
        for(int i=0;i<len;i++){
            int sum=0;
            for(int j=0;j<len;j++){
                if(a[i]==a[j])
                    sum++;
            }
            if(sum==1){
                flag=false;
                cout<<a[i]<<endl;
                break;
            }
        }
        if(flag)
            cout<<-1<<endl;
    }
    return 0;
}

发表于 2020-08-16 17:37:26 回复(0)
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.next();
            //构建二维矩阵统计字符出现的次数,只出一次列的和为1,即输出
            int dp[][]=new int [str.length()][str.length()];
            String chr="-1";
            for(int i=0;i<str.length();i++){
                int colSum=0;
                for(int j=0;j<str.length();j++){
                    if(str.charAt(i)==str.charAt(j)){
                        dp[i][j]=1;
                    }else{
                        dp[i][j]=0;
                    }
                    colSum+=dp[i][j];
                }
                if(colSum==1){
                    chr=String.valueOf(str.charAt(i));
                    break;
                }
            }
                System.out.println(chr);
       }
  }
}

发表于 2020-06-08 11:22:10 回复(0)
#include<stdio.h>
(737)#include<string.h>
int main()
{
    char S[1024] = {0};
    gets(S);
    int count, i, j, len = 0;
    len = strlen(S);
    for(i = 0; i < len; i++)
    {
        for(j = 0; j < len; j++)
        {
            if(S[i] == S[j])
            {
                count++;
            }
        }
        if (1 == count)
        {
            printf("%c\n", S[i]);
            return 0;
        }
        else
        {
            count = 0;
        }
    }
    if(0 == count)
    {
        printf("-1");
    }
    return 0;
}
找毛病


编辑于 2020-04-15 14:11:31 回复(1)
public class Main{
     public static void main(String[] args) {
        java.util.Scanner scanner = new java.util.Scanner(System.in);
        while (scanner.hasNext()){
            String inputStr = scanner.next();
            int[] charAppearsCounterArr = new int[26];
            int[] charAppearsIndexArr = new int[26];
            char[] inputStrCharArr = inputStr.toCharArray();
            for(int i = 0; i < inputStrCharArr.length; i++){
                char charTmp = inputStrCharArr[i];
                int charCounter = charAppearsCounterArr[charTmp - 97];
                charAppearsCounterArr[charTmp - 97] = charCounter + 1;
                if(charCounter == 0){
                    charAppearsIndexArr[charTmp - 97] = i;
                }
            }
            int targetChar = -1;
            for(int i = 0; i < 26; i ++){
                if(charAppearsCounterArr[i] == 1){
                    if(targetChar >= 0){
                        if(charAppearsIndexArr[targetChar] > charAppearsIndexArr[i]){
                            targetChar = i;
                        }
                    }else {
                        targetChar = i;
                    }
                }
            }
            if(targetChar >= 0){
                System.out.println((char)(targetChar + 97));
            }else {
                System.out.println("-1");
            }
        }
    }
}

发表于 2020-03-29 16:54:59 回复(0)

问题信息

难度:
634条回答 54714浏览

热门推荐

通过挑战的用户

查看代码