oj phone number

这段代码实现了一个电话号码的存储和查找算法。通过一个结构体`Node`表示电话号码树节点,`Insert`函数用于插入电话号码,`Search`函数用于查找电话号码出现的次数。在主函数中,读取一组电话号码并存储到树中,然后检查是否存在重复的电话号码,如果存在则输出"NO",否则输出"YES"。
摘要由CSDN通过智能技术生成

在这里插入图片描述

#include <iostream>
#include <string>
#include <list>
using namespace std;

struct Node
{
	int count;
	Node *child[10];
	Node()
	{
		count = 0;
		int i;
		for (i = 0; i < 10; i++)
			child[i] = 0;
	}
};
Node* current;
Node* newNode;

void Insert(Node* root, string phoneNum)
{
	current = root;
	for (int i = 0; i < phoneNum.length(); i++)
	{
		int num = phoneNum[i] - '0';
		if (current->child[num] != NULL)
		{
			current = current->child[num];
			++(current->count);
		}
		else
		{
			newNode = new Node;
			++(newNode->count);
			current->child[num] = newNode;
			current = newNode;
		}
	}
}

int Search(Node* root, string phoneNum)
{
	current = root;
	for (int i = 0; i < phoneNum.length(); i++)
	{
		int num = phoneNum[i] - '0';
		if (current->child[num] == NULL)
		{
			return 0;
		}
		current = current->child[num];
	}
	return current->count;
}

int main()
{
	int num = 0;
	string phoneNum;
	list<string> vStr;

	while (cin >> num)
	{
		if (num == 0)
		{
			break;
		}
		bool flag = false;
		Node* root = new Node;
		for (int i = 0; i < num; i++)
		{
			cin >> phoneNum;
			vStr.push_back(phoneNum);
			Insert(root, phoneNum);
		}
		list<string>::iterator it = vStr.begin();
		for (; it != vStr.end(); it++)
		{
			if (Search(root, *it) - 1)
			{
				flag = true;
				break;
			}
		}
		if (flag)
			cout << "NO" << endl;
		else
			cout << "YES" << endl;
		vStr.clear();
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值