zoukankan      html  css  js  c++  java
  • 389. Find the Difference

    原题:

    389. Find the Difference

    解题:

    采用map字典进行计数,由于只增加了一个字符,那么其他字符的在s和t中均各自出现,所以,可以先遍历串t,建立字符:计数字典,然后遍历串s,每个字符对应的计数就减一,只有增加的字符对应的计数才是1,其余的均为0;

    class Solution {
    public:
    	char findTheDifference(string s, string t) 
    	{
    		int i = 0;
    		int j = 0;
    		map <char,int> maptmp;
    		for(i = 0;i < t.length();i++)
    		{
    			maptmp[t[i]]++;
    		}
    		for(j = 0;j < s.length();j++)
    		{
    			if(maptmp.find(s[j])!= maptmp.end())
    			{
    				maptmp[s[j]]--;
    			}			
    		}
    		for(i = 0;i < t.length();i++)
    		{
    			if(maptmp[t[i]] == 1)
    			{
    				return t[i];
    			}
    		}
    	}
    };
    

     改进:先遍历s,然后遍历t,当计数小于0时则跳出循环,可以减少查找次数,同时用无序的map比有序map要快

    class Solution {
    public:
    	char findTheDifference(string s, string t) 
    	{
    		int i = 0;
    		int j = 0;
    		unordered_map <char,int> maptmp;
    		for(i = 0;i < s.length();i++)
    		{
    			maptmp[s[i]]++;
    		}
    		for(j = 0;j < t.length();j++)
    		{
    			maptmp[t[j]]--;
    			if(maptmp[t[j]] < 0)
    			{
    				return t[j];
    			}				
    		}
    	}
    };
    

      

  • 相关阅读:
    IOS-JSON数据解析
    IOS-APP发布资料收集
    IOS-webService
    ASP.NET MVC学习之路:模板页
    io流
    线程
    事件监听
    java基础面试题
    递归调用
    三目运算: x?y:z
  • 原文地址:https://www.cnblogs.com/xqn2017/p/8475992.html
Copyright © 2011-2022 走看看