题解 | 记录点赞用户

记录点赞用户

https://www.nowcoder.com/practice/19a766a67cdc4eb0a354d70597cf008b

import java.util.*;

public class Main {

    public static void main(String[] args) {
        LikeRecorder recorder = new LikeRecorderImpl();

        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            String name = scanner.next();
            recorder.like(name);
        }

        System.out.println(Arrays.toString(recorder.getLikeUsers()));
    }

}

/**
 * 点赞记录器
 */
interface LikeRecorder {

    /**
     * 若用户没有点赞过,则记录此次点赞行为。
     * 若用户曾经点赞过,则删除用户点赞记录。
     *
     * @param username 用户名
     */
    void like(String username);

    /**
     * 返回所有点赞的用户名
     *
     * @return 用户名数组
     */
    String[] getLikeUsers();

}

class LikeRecorderImpl implements LikeRecorder {

    // write your code here......
    private boolean likeFlag = false;
    private static HashSet<String> set = new HashSet<>();

    public void like(String username){
        if(set.contains(username)){
            set.remove(username);
        }else{
            set.add(username);
        }
    }

    public String[] getLikeUsers(){
        String [] strs = new String[set.size()];
        List<String> list = new ArrayList<>();
        int index = 0;
        for(String s : set){
            strs[index] = s;
            index++;
        }
        return strs;
    }
}











全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务