/*
* 描述: 找出字符串中第一個只出現一次的字符
* 詳細描述:
* 接口說明
* 原型:
* bool FindChar(char* pInputString, char* &pChar);
* 輸入參數:
* char* pInputString:字符串
* 輸出參數(指針指向的內存區域保證有效):
* char* pChar:第一個只出現一次的字符
* 如果無此字符 請輸出'.'
* 知識點: 字符串,循環
* 題目來源: 內部整理
* 練習階段: 初級
* 運行時間限制: 10Sec
* 內存限制: 128MByte
* 輸入:
* 輸入一串字符
* 輸出:
* 輸出一個字符
* 樣例輸入: asdfasdfo
* 樣例輸出: o
*/
#include <iostream>
#include <string>
#include <string.h>
#include <map>
#include <vector>
using namespace std;
struct MY_Pairs
{
int count;
map<int,int> position;
};
void Input(std::string &str);
bool FindChar(char* pInputString, char* pChar);
int main()
{
std::string str;
char* pInputString;
char pChar;
Input(str);
pInputString = const_cast<char*>(str.c_str());
bool result = FindChar(pInputString, &pChar);
if(!result)
{
return -1;
}
std::cout << pChar << endl;
system("pause");
return 0;
}
void Input(std::string &str)
{
getline(std::cin,str,'\n');
return;
}
bool FindChar(char* pInputString, char* pChar)
{
map<char,MY_Pairs> Statistics;
map<char,MY_Pairs>::iterator iter;
int len = strlen(const_cast<const char*>(pInputString));
char c;
/* 字符串爲空字符串 */
if(len==0)
{
return false;
}
/* 分類 */
for(int i=0;i<len;i++)
{
c = pInputString[i];
iter = Statistics.find(c);
/* 找到這個關鍵字 */
if(iter!=Statistics.end())
{
iter->second.count++;
iter->second.position[iter->second.count]++;
}
else /* 沒找到 */
{
MY_Pairs pairs_temp;
pairs_temp.count = 0;
pairs_temp.count++;
pairs_temp.position[pairs_temp.count]=i;
Statistics.insert(map<char,MY_Pairs>::value_type(c,pairs_temp));
}
}
/* 找出出現次數爲1的字符 */
int Firstposition = len;
map<int,int>::iterator iter_first;
for(map<char,MY_Pairs>::iterator m_iter=Statistics.begin();m_iter!=Statistics.end();m_iter++)
{
if(m_iter->second.count == 1)
{
iter_first = m_iter->second.position.begin();
int kk = iter_first->second;
if(kk<Firstposition)
{
Firstposition = kk;
}
}
}
if(Firstposition==len)
{
const char pp2 = '.';
memcpy(pChar,&pp2,1);
return true;
}
/* 從字符串中取一個字符 */
const char pp = pInputString[Firstposition];
memcpy(pChar,&pp,1);
return true;
}