美文网首页
给定字符串str,搜索第m个只出现n次的字符

给定字符串str,搜索第m个只出现n次的字符

作者: 一语漂泊何处寻 | 来源:发表于2019-11-05 23:02 被阅读0次

    给定字符串"tervest",搜索第2个只出现1次的字符,输出v。

    
    public static String searchMNChar(String str,int m,int n){
    
      int mCount =0;
    
      HashSet singleChar =new HashSet<>(str.length());
    
      for (int i =0 ; i < str.length() ; i ++){
    
        if (singleChar.contains(str.charAt(i))){
    
          continue;
    
        }
    
        singleChar.add(str.charAt(i));
    
        int nCount =0;
    
        for (int j = i; j < str.length(); j++) {
    
           if (str.charAt(i) == str.charAt(j)){
    
              nCount++;
    
          }
    
        }
    
        if (nCount == n){
    
          mCount++;
    
        }
    
        if (mCount == m){
    
          return str.substring(i,++i);
    
        }
    
      }
    
      return null;
    
    }
    
    

    相关文章

      网友评论

          本文标题:给定字符串str,搜索第m个只出现n次的字符

          本文链接:https://www.haomeiwen.com/subject/mtkybctx.html