929. Unique Email Address

If you add a plus ('+') in the local name, everything after the first plus sign will be ignored. This allows certain emails to be filtered, for example m.y+name@email.com will be forwarded to my@email.com.  (Again, this rule does not apply for domain names.)

It is possible to use both of these rules at the same time.

Given a list of emails, we send one email to each address in the list.  How many different addresses actually receive mails? 

 

Example 1:

Input: ["test.email+alex@leetcode.com","test.e.mail+bob.cathy@leetcode.com","testemail+david@lee.tcode.com"]
Output: 2
Explanation: "testemail@leetcode.com" and "testemail@lee.tcode.com" actually receive mails

 

本菜鸟代码:

class Solution {
    public int numUniqueEmails(String[] emails) {
        HashSet stringSet = new HashSet();
        String s = null;
        for(int i = 0;i<emails.length;i++){
            s = "";
            int flagplus = 0;
            int flagat = 0;
            for(int j = 0;j<emails[i].length();j++){
                char ss = emails[i].charAt(j);
                if(ss!='@'&&flagplus==0){
                    if(ss!='.'&&ss!='+')  s+=ss;
                    else{
                        if(ss=='+') flagplus = 1;
                    }
                }else{
                    if(ss=='@'||flagat==1) {
                        flagat = 1;
                        s+=ss;
                    }
                }
            }
            stringSet.add(s);
        }
        return stringSet.size();
    }
}
我的思路是:
对于‘+’ 和‘@’设置两个flag,如果遇到‘+’,就一直不添加字符,直到遇到了‘@’。在‘@’以后都直接添加字符。为了统计不重复的字符串,我用了HashSet来存储。最后返回HashSet的大小。

 

 

官方的答案是:

class Solution {
    public int numUniqueEmails(String[] emails) {
        Set<String> seen = new HashSet();
        for (String email: emails) {
            int i = email.indexOf('@');
            String local = email.substring(0, i);
            String rest = email.substring(i);
            if (local.contains("+")) {
                local = local.substring(0, local.indexOf('+'));
            }
            local = local.replaceAll(".", "");
            seen.add(local + rest);
        }

        return seen.size();
    }
}

官方的答案非常清楚。但是用到了很多子函数:indexOf , contains, substring,replaceAll.

 

 

@Getter @Setter @NoArgsConstructor @AllArgsConstructor @Table(name = “user_info”) @Entity public class UserInfo { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false) private String username; @Column(nullable = false) private String password; @Column(nullable = false, unique = true) private String email; private String address; private Integer status = 0; } @Slf4j @RestController @RequestMapping(“/admin”) public class AdminController { @Autowired private AdminService adminService; @PostMapping("/add") public ResponseEntity<UserRegisterSuccessDTO> addUser(@Valid @RequestBody UserRegisterDTO userRegisterDTO) { try { UserRegisterSuccessDTO response = adminService.addUser(userRegisterDTO); log.info("{} added", userRegisterDTO.getUsername()); return ResponseEntity.ok(response); } catch (UnauthorizedException e) { return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null); } } @DeleteMapping("/delete") public ResponseEntity<ReponseDTO> deleteUserByEmail(@Valid @RequestBody RequestDTO requestDTO) { try { ReponseDTO response = adminService.deleteUserByEmail(requestDTO.getEmail()); log.info("{} deleted", response.getUsername()); return ResponseEntity.ok(response); } catch (UnauthorizedException e) { return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null); } } @PutMapping("/update") public ResponseEntity<ReponseDTO> updateUser(@Valid @RequestBody UserDTO userDTO) { try { ReponseDTO response = adminService.updateUser(userDTO); log.info("{} updated", response.getUsername()); return ResponseEntity.ok(response); } catch (UnauthorizedException e) { return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null); } } @GetMapping("/get") public ResponseEntity<UserInfo> getUserByEmail(@Valid @RequestBody RequestDTO requestDTO) { try { UserInfo response = adminService.getUserByEmail(requestDTO.getEmail()); log.info("{} searched", response.getUsername()); return ResponseEntity.ok(response); } catch (UnauthorizedException e) { return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null); } } } @Slf4j @Service public class AdminServiceImpl implements AdminService{ @Autowired private UserRepository userRepository; @Value("${app.max-users}") private long maxUserCount; @Override public UserRegisterSuccessDTO addUser(UserRegisterDTO userRegisterDTO) { // 检查是否达到最大用户数 long currentCount = userRepository.count(); if(currentCount >= maxUserCount) { log.error("Maximum user limit reached"); throw new UnauthorizedException("Maximum user limit reached"); } // 检查邮箱是否重复 if (userRepository.existsByEmail(userRegisterDTO.getEmail())) { log.error("Email already exists"); throw new UnauthorizedException("Email already exists"); } // 创建用户 UserInfo user = new UserInfo(); user.setUsername(userRegisterDTO.getUsername()); user.setPassword(userRegisterDTO.getPassword()); user.setEmail(userRegisterDTO.getEmail()); user.setAddress(userRegisterDTO.getAddress()); userRepository.save(user); return new UserRegisterSuccessDTO("User added successfully", user.getId()); } @Transactional @Override public ReponseDTO deleteUserByEmail(String email) { if (!userRepository.existsByEmail(email)) { log.error("User not existed"); throw new RuntimeException("User not existed"); } UserInfo user = userRepository.findByEmail(email).get(); userRepository.deleteByEmail(email); return new ReponseDTO(user.getUsername()); } @Override public ReponseDTO updateUser(UserDTO userDTO) { Optional<UserInfo> userOpt = userRepository.findByEmail(userDTO.getEmail()); UserInfo user = userOpt.get(); if (userDTO.getUsername() != null && !userDTO.getUsername().trim().isEmpty()) { user.setUsername(userDTO.getUsername()); } if (userDTO.getPassword() != null && !userDTO.getPassword().trim().isEmpty()) { user.setPassword(userDTO.getPassword()); } if (userDTO.getEmail() != null && !userDTO.getEmail().trim().isEmpty()) { user.setEmail(userDTO.getEmail()); } if (userDTO.getAddress() != null && !userDTO.getAddress().trim().isEmpty()) { user.setAddress(userDTO.getAddress()); } userRepository.save(user); return new ReponseDTO(user.getUsername()); } @Override public UserInfo getUserByEmail(String email) { if (!userRepository.existsByEmail(email)) { log.error("User not existed"); throw new RuntimeException("User not existed"); } return userRepository.findByEmail(email).get(); } } public interface UserRepository extends JpaRepository<UserInfo, Long> { boolean existsByEmail(String email); Optional findByEmail(String email); @Override long count(); void deleteByEmail(String email); } spring: profile: mysql datasource: url: jdbc:mysql://localhost:3306/mysql?useSSL=false&serverTimezone=GMT%2B8 username: root password: 123032 jpa: hibernate: ddl-auto: update show-sql: true properties: hibernate: dialect: org.hibernate.dialect.MySQL8Dialect management: endpoints: web: exposure: include: “*” endpoint: health: show-details: always app: max-users: 20 已经使用mysql实现了用户的增删改查,现在想切换mongo数据库来实现相应功能,并且在Controller层不变的情况下,实现通过简单修改配置后,更换不同的数据源,相关代码和配置如上,应该怎么加代码和改配置
08-30
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值