You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called "bulls") and how many digits match the secret number but locate in the wrong position (called "cows"). Your friend will use successive guesses and hints to eventually derive the secret number.

Write a function to return a hint according to the secret number and friend's guess, use A to indicate the bulls and B to indicate the cows.

Please note that both secret number and friend's guess may contain duplicate digits.

Example 1:

Input: secret = "1807", guess = "7810"

Output: "1A3B"

Explanation: 1 bull and 3 cows. The bull is 8, the cows are 0, 1 and 7.

Example 2:

Input: secret = "1123", guess = "0111"

Output: "1A1B"

Explanation: The 1st 1 in friend's guess is a bull, the 2nd or 3rd 1 is a cow.

题意:

猜字游戏。

我负责猜,

你负责给提示:数字和位置都对,bulls++。数字对位置不对,cows++。

思路:

挨个扫字符串s,

挨个扫字符串g

若s当前字符等于g的字符,bulls++

用int[] map = new int[256]建一个简化版的HashMap

思路类似valid anagram

s当前字符在map里标记为++

p当前字符在map里标记为--

那么,若s当前字符已经被标记为--,说明p的字符来标记过,即它们字符相同但位置不同,cow++。

同理,若p当前字符已经被标记为++, 说明s的字符来标记过, 即它们字符相同但位置不同,cow++。

代码:

 class Solution {
public String getHint(String secret, String guess) {
// corner
if(secret.length() != guess.length()) return false;
int[] map = new int[256];
int bull = 0;
int cow = 0;
for(int i = 0; i < secret.length();i++){
char s = secret.charAt(i);
char g = guess.charAt(i);
if(s == g){
bull++;
}else{
if(map[s]<0) cow++;
if(map[g]>0) cow++;
map[s]++;
map[g]--;
}
}
return bull +"A" + cow + "B";
}
}

最新文章

  1. UML类图符号 各种关系说明以及举例
  2. Linux I/O多路复用
  3. javascript进阶系列专题:作用域与作用域链
  4. Web API 接口
  5. 边工作边刷题:70天一遍leetcode: day 81
  6. 《30天自制操作系统》09_day_学习笔记
  7. 夺命雷公狗---Thinkphp----13之前台的头尾分离和导航分离
  8. Spring整合Hibernate图文步骤
  9. 安卓Intent(隐式)
  10. AJAX 表单提交 文件上传
  11. iOS之网络编程
  12. Problem M
  13. ajaxSetup设置Ajax请求的默认值
  14. Java公开课-02.抽象类和接口
  15. Spring框架-IOC和AOP简单总结
  16. 阿里云HBase全新发布X-Pack 赋能轻量级大数据平台
  17. python 几分钟前,几小时前,几天前转为时间戳
  18. Qt_颜色选择对话框(QColorDialog)
  19. 虚拟机安装centos6.6全步骤
  20. getServletContext()接口解析(收藏)

热门文章

  1. gearman在虚拟机上运行没有自动开启的处理
  2. OpenGL 画出雷达动态扫描效果(一)
  3. Spring学习之AOP详解
  4. 在 mvc 4 中使用 unity 进行依赖注入
  5. Intro.js的简介和用法
  6. python学习之----异常处理小示例
  7. Bogart gData.vb
  8. centos启用root账号登陆telnet
  9. mysql5.7.13 使用笔记
  10. RocketMQ初探(五)之RocketMQ4.2.6集群部署(单Master+双Master+2m+2s+async异步复制)