校招算法笔面试 | 华为机试-找出字符串中第一个只出现一次的字符

题目## 题目

题目链接

解题思路

  1. 题目要求:

    • 找出字符串中第一个只出现一次的字符
    • 如果不存在输出-1
    • 字符串长度不超过1000
  2. 实现思路:

    • 使用哈希表记录每个字符出现的次数
    • 再次遍历字符串,找到第一个出现次数为1的字符
    • 如果不存在这样的字符,返回-1
  3. 优化方案:

    • 可以使用数组代替哈希表(因为字符集有限)
    • 使用两次遍历确保保持字符的原始顺序

代码

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

int main() {
    string str;
    while (cin >> str) {
        // 统计每个字符出现的次数
        unordered_map<char, int> count;
        for (char c : str) {
            count[c]++;
        }
        
        // 找第一个只出现一次的字符
        char result = '\0';
        for (char c : str) {
            if (count[c] == 1) {
                result = c;
                break;
            }
        }
        
        if (result == '\0') {
            cout << -1 << endl;
        } else {
            cout << result << endl;
        }
    }
    return 0;
}
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String str = sc.next();
            
            // 统计每个字符出现的次数
            Map<Character, Integer> count = new HashMap<>();
            for (char c : str.toCharArray()) {
                count.put(c, count.getOrDefault(c, 0) + 1);
            }
            
            // 找第一个只出现一次的字符
            char result = '\0';
            for (char c : str.toCharArray()) {
                if (count.get(c) == 1) {
                    result = c;
                    break;
                }
            }
            
            if (result == '\0') {
                System.out.println(-1);
            } else {
                System.out.println(result);
            }
        }
    }
}
while True:
    try:
        s = input()
        
        # 统计每个字符出现的次数
        count = {}
        for c in s:
            count[c] = count.get(c, 0) + 1
        
        # 找第一个只出现一次的字符
        result = None
        for c in s:
            if count[c] == 1:
                result = c
                break
        
        print(result if result is not None else -1)
        
    except EOFError:
        break

算法及复杂度

  • 算法:哈希表统计
  • 时间复杂度: O ( n ) \mathcal{O}(n) O(n) - 需要两次遍历字符串
  • 空间复杂度: O ( k ) \mathcal{O}(k) O(k) - k k k 为字符集大小,本题中 k k k 最大为所有可能的字符数

题目链接

解题思路

这是一个扑克牌大小比较问题。需要处理以下几种牌型和比较规则。

牌型和规则

  1. 牌型:个子、对子、顺子、三个、炸弹、对王
  2. 大小规则:对王 > 炸弹 > 其他(同类型比较)
  3. 牌面大小:3 < 4 < … < K < A < 2 < joker < JOKER

代码

C++实现

#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <unordered_map>
#include <algorithm>
using namespace std;

class Solution {
private:
    unordered_map<string, int> values = {
        {"3",3}, {"4",4}, {"5",5}, {"6",6}, {"7",7}, {"8",8}, {"9",9}, {"10",10},
        {"J",11}, {"Q",12}, {"K",13}, {"A",14}, {"2",15}, {"joker",16}, {"JOKER",17}
    };
    
    pair<int,int> getTypeAndValue(string hand) {
        stringstream ss(hand);
        vector<string> cards;
        string card;
        while (ss >> card) cards.push_back(card);
        
        // 对王判断
        if (cards.size() == 2 && card == "JOKER" && cards[0] == "joker")
            return {5, 17};
            
        // 炸弹判断
        if (cards.size() == 4 && card == cards[0] && cards[1] == cards[0] && cards[2] == cards[0])
            return {4, values[card]};
            
        // 其他牌型
        if (cards.size() == 1)  // 单张
            return {1, values[card]};
        if (cards.size() == 2 && card == cards[0])  // 对子
            return {2, values[card]};
        if (cards.size() == 3 && card == cards[0] && cards[1] == cards[0])  // 三个
            return {3, values[card]};
        if (cards.size() == 5) {  // 顺子
            vector<int> vals;
            for (string& c : cards)
                vals.push_back(values[c]);
            sort(vals.begin(), vals.end());
            if (vals[0] >= 3 && vals[4] <= 14)
                if (vals[4] - vals[0] == 4)
                    return {0, vals[4]};
        }
        return {-1, 0};
    }
    
public:
    string comparePoker(string hand1, string hand2) {
        auto [type1, value1] = getTypeAndValue(hand1);
        auto [type2, value2] = getTypeAndValue(hand2);
        
        if (type1 == -1 || type2 == -1)
            return "ERROR";
            
        if (type1 == 5) return hand1;
        if (type2 == 5) return hand2;
        
        if (type1 == 4 && type2 != 4) return hand1;
        if (type2 == 4 && type1 != 4) return hand2;
        
        if (type1 == type2)
            return value1 > value2 ? hand1 : hand2;
            
        return "ERROR";
    }
};

int main() {
    string line;
    while (getline(cin, line)) {
        size_t pos = line.find('-');
        string hand1 = line.substr(0, pos);
        string hand2 = line.substr(pos + 1);
        Solution sol;
        cout << sol.comparePoker(hand1, hand2) << endl;
    }
    return 0;
}
import java.util.*;

public class Main {
    static class Solution {
        private Map<String, Integer> values = new HashMap<String, Integer>() {{
            put("3",3); put("4",4); put("5",5); put("6",6); put("7",7);
            put("8",8); put("9",9); put("10",10); put("J",11); put("Q",12);
            put("K",13); put("A",14); put("2",15); put("joker",16); put("JOKER",17);
        }};
        
        private int[] getTypeAndValue(String hand) {
            String[] cards = hand.split(" ");
            
            // 对王判断
            if (cards.length == 2 && cards[1].equals("JOKER") && cards[0].equals("joker"))
                return new int[]{5, 17};
                
            // 炸弹判断
            if (cards.length == 4 && cards[0].equals(cards[1]) && cards[1].equals(cards[2]) 
                && cards[2].equals(cards[3]))
                return new int[]{4, values.get(cards[0])};
                
            // 其他牌型
            if (cards.length == 1)  // 单张
                return new int[]{1, values.get(cards[0])};
            if (cards.length == 2 && cards[0].equals(cards[1]))  // 对子
                return new int[]{2, values.get(cards[0])};
            if (cards.length == 3 && cards[0].equals(cards[1]) && cards[1].equals(cards[2]))  // 三个
                return new int[]{3, values.get(cards[0])};
            if (cards.length == 5) {  // 顺子
                List<Integer> vals = new ArrayList<>();
                for (String card : cards)
                    vals.add(values.get(card));
                Collections.sort(vals);
                if (vals.get(0) >= 3 && vals.get(4) <= 14)
                    if (vals.get(4) - vals.get(0) == 4)
                        return new int[]{0, vals.get(4)};
            }
            return new int[]{-1, 0};
        }
        
        public String comparePoker(String hand1, String hand2) {
            int[] result1 = getTypeAndValue(hand1);
            int[] result2 = getTypeAndValue(hand2);
            
            if (result1[0] == -1 || result2[0] == -1)
                return "ERROR";
                
            if (result1[0] == 5) return hand1;
            if (result2[0] == 5) return hand2;
            
            if (result1[0] == 4 && result2[0] != 4) return hand1;
            if (result2[0] == 4 && result1[0] != 4) return hand2;
            
            if (result1[0] == result2[0])
                return result1[1] > result2[1] ? hand1 : hand2;
                
            return "ERROR";
        }
    }
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNextLine()) {
            String line = sc.nextLine();
            String[] hands = line.split("-");
            Solution sol = new Solution();
            System.out.println(sol.comparePoker(hands[0], hands[1]));
        }
    }
}
def get_card_value(card):
    values = {'3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, '10':10,
              'J':11, 'Q':12, 'K':13, 'A':14, '2':15, 'joker':16, 'JOKER':17}
    return values.get(card, 0)

def get_type_and_value(cards):
    cards = cards.split()
    
    # 对王判断
    if sorted(cards) == ['JOKER', 'joker']:
        return 5, 17
    
    # 炸弹判断
    if len(cards) == 4 and len(set(cards)) == 1:
        return 4, get_card_value(cards[0])
    
    # 其他牌型判断
    if len(cards) == 1:  # 单张
        return 1, get_card_value(cards[0])
    elif len(cards) == 2 and cards[0] == cards[1]:  # 对子
        return 2, get_card_value(cards[0])
    elif len(cards) == 3 and len(set(cards)) == 1:  # 三个
        return 3, get_card_value(cards[0])
    elif len(cards) == 5:  # 顺子
        values = sorted([get_card_value(c) for c in cards])
        if values[0] >= 3 and values[-1] <= 14:  # 不能包含2
            if values == list(range(values[0], values[0] + 5)):
                return 0, values[-1]
    
    return -1, 0  # 非法输入

def compare_poker(hand1, hand2):
    type1, value1 = get_type_and_value(hand1)
    type2, value2 = get_type_and_value(hand2)
    
    if type1 == -1 or type2 == -1:
        return "ERROR"
    
    # 对王最大
    if type1 == 5:
        return hand1
    if type2 == 5:
        return hand2
    
    # 炸弹比较
    if type1 == 4 and type2 != 4:
        return hand1
    if type2 == 4 and type1 != 4:
        return hand2
    
    # 同类型比较
    if type1 == type2:
        return hand1 if value1 > value2 else hand2
    
    return "ERROR"  # 不同类型无法比较

# 主程序
while True:
    try:
        line = input().strip()
        hand1, hand2 = line.split('-')
        print(compare_poker(hand1, hand2))
    except:
        break

算法及复杂度

算法分析

  1. 牌型判断:

    • 使用字典存储牌面值
    • 通过牌数和重复情况判断牌型
    • 顺子需要检查连续性和范围
  2. 大小比较:

    • 先判断特殊牌型(对王、炸弹)
    • 再判断是否同类型
    • 最后比较牌面大小

复杂度分析

  • 时间复杂度: O ( 1 ) \mathcal{O}(1) O(1) - 因为牌数最多5张,可以视为常数
  • 空间复杂度: O ( 1 ) \mathcal{O}(1) O(1) - 只需要常量额外空间
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值