zoukankan      html  css  js  c++  java
  • 面试题41:从字符串中找到第一个只出现一次的字符

    思路:数组模拟哈希表,保存字符和其出现次数的映射关系,然后从头开始扫描字符串即可求解

    代码如下:

    #include "stdafx.h"
    #include <iostream>
    using namespace std;
    
    //从字符串中找到第一个只出现一次的字符
    char FirstNotRepeatChar(char *Str)
    {
    	if (Str == NULL)
    	{		
    		return NULL;
    	}
    
        //用数组模拟哈希表
    	int HashTable[256] = {0};
    	char *pCur = Str;
    	char cResult = '#';
    	while ( *pCur != '' )
    	{
    		HashTable[*pCur++]++;
    	}
    
    	pCur = Str;//重新指回字符串的首字符
    	while (*pCur != '')
    	{
    		if (HashTable[*pCur] == 1)
    		{
    			cResult = *pCur;
                break; 
    		}
    		pCur++;
    	}
    
    	if (cResult == '#')
    	{
    		cout << "不存在只出现一次的字符!" << endl;
    	}
    	return cResult;
    }
    
    
    int _tmain(int argc, _TCHAR* argv[])
    {
    	char *Str1 = "abaccdeff";//有序
    	char *Str2 = "aaaaaaa";//没有只出现一次的字符
        char *Str3 = "bacffcde";//无序
    	char *Str4 = "fbacde";//无序且都只出现一次
        cout << FirstNotRepeatChar(Str1) << endl;
    	cout << FirstNotRepeatChar(Str2) << endl;
    	cout << FirstNotRepeatChar(Str3) << endl;
    	cout << FirstNotRepeatChar(Str4) << endl;
    	system("pause");
    	return 0;
    }
    
    

    运行结果:


     

  • 相关阅读:
    如何让WPF程序用上MVVM模式
    wpf开源界面收集
    WPF界面框架的设计
    WPF数据验证
    WPF实用知识点
    wpf的MVVM框架
    数据库中树形结构的表的设计
    ASP.NET MVC 分部视图
    好用的 Visual Studio插件
    ASP.NET MVC3中Controller与View之间的数据传递总结
  • 原文地址:https://www.cnblogs.com/keanuyaoo/p/3304169.html
Copyright © 2011-2022 走看看