// 013.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
//思路:字符的ASCI碼值從0到255,設立一個數組用於記錄每一個值出現的次數。
//此數組的最大控件爲256,則可以統計出每個ASCI值出現的次數。
//出現次數爲1次的字符被篩選出來,在字符緩衝區中提取其對應的下標。找出
//下標最小的同時只出現一次的字符。
bool FindFirstDisplayCharacter(char *pBuffer, int &minPos)
{
if (NULL == pBuffer)
{
return false;
}
int len=0;
char *pBegin = pBuffer;
while(*pBegin != '\0')
{
len++;
pBegin++;
}
const int MAX_SIZE = 256;
int timesofCharacter[MAX_SIZE];
int i=0;
for (i=0; i<MAX_SIZE; i++)
{
timesofCharacter[i] = 0;
}
for (i=0; i<len; i++)
{
int index = pBuffer[i];
for (int j=0; j<MAX_SIZE; j++)
{
if (j == index)
{
++timesofCharacter[index];
}
}
}
//出現一次的字符有:
int count = 0;
char pTemp[MAX_SIZE];//保存出現一次的字符
for (i=0; i<MAX_SIZE; i++)
{
if (timesofCharacter[i] == 1)
{
pTemp[count] = i;
count++;
}
}
bool bFirst = true;
int pos = 0;
for (int j=0; j<count; j++)
{
for (i=0; i<len; i++)
{
if (pTemp[j] == pBuffer[i])
{
if (bFirst)//第一次出現相等字符時
{
bFirst = false;
pos = i;
}
else
{
if (i < pos)
{
pos = i;//記錄最小位置
}
}
}
}
}
minPos = pos;
return true;
}
//改進版本
char FindFirstChar(char *pBuf)
{
if (NULL == pBuf)
{
return 0;
}
const int MAX_SIZE = 256;
int timesofCharacter[MAX_SIZE];
int i = 0;
for (i=0; i<MAX_SIZE; i++)
{
timesofCharacter[i] = 0;
}
char *pCur = pBuf;
while (*pCur != '\0')
{
timesofCharacter[*pCur]++;
pCur++;
}
pCur = pBuf;
while(*pCur != '\0')
{
if (timesofCharacter[*pCur] == 1)
{
return *pCur;
}
pCur++;
}
return 0;
}
//(13)-第一個只出現一次的字符
int main(int argc, char* argv[])
{
char pBuffer[] = "abbaccdeff";
/* int minPos = -1;
FindFirstDisplayCharacter(pBuffer, minPos);
char tmp = pBuffer[minPos];
*/
char tmp = FindFirstChar(pBuffer);
printf("%c\n", tmp);
return 0;
}
013-字符串
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.