20210804力扣字符串类题(java)

本文主要解析了力扣(LeetCode)中涉及字符串处理的几道题目,包括计数二进制子串、环绕字符串唯一子串、TinyURL的加密解密等。通过Java编程语言,探讨了各种解题思路,如使用HashMap存储关键信息、转换时间单位简化计算等。文章总结了在解决这些问题时遇到的难点和解决方法。
摘要由CSDN通过智能技术生成


力扣第696题:计数二进制子串

这道题是读懂了,但是怎么做却不会,看了答案,找到他们的每个连续的0和1,把相邻的小的数加起来就行。
果然很简单了,但是自己在写相邻时候的计数,还会写错,不应该。

class Solution {
   
    public int countBinarySubstrings(String s) {
   
      List<Integer> counts = new ArrayList<>();
      int num = 0;
        while(num<s.length())
      {
   
          char c = s.charAt(num);
          int count = 0 ;
          while(num<s.length()&&s.charAt(num)==c)
          {
   
              num++;
              count++;
          }
          counts.add(count);
      }

    int ans = 0;
      for(int i = 1 ; i<counts.size();i++)
    {
   
        ans+=Math.min(counts.get(i),counts.get(i-1));
    }
    return ans;

    }
}

力扣第467题:环绕字符串中唯一的子字符串

这道题我不会做,我看了评论,我想到了找到最长的串,然后累加就可以得到最多的子串,比如‘abcd’,那么长度是4;结果应该是1+2+3+4 = 10;但是还是不会写。热评建立了一个长度为26的数组,就是记录每个当前字符所占有的最多的字符串长度,如‘abc’,那么a是1,b是2,c是3;找到最后一位就算找完了,就可以把这些累计加起来就是最长的。

class Solution {
   
    public int findSubstringInWraproundString(String p) {
   
       int n = p.length();
       int curcount = 1;
       int count[] = new int[26];
       char str[] = p.toCharArray();

       for(int i = 0 ;i<n;i++)
       {
   
           if(i>0&&(str[i] - str[i-1]==1||str[i-1]-str[i]==25))
           {
   
               curcount++;
           }
           else
           {
   
               curcount = 1;
           }
           count[str[i] - 'a'] = Math.max(curcount,count[str[i] - 'a']);
       }

            int res = 0 ;
            for(int temp :count)    res+=temp;
            return res;
    }
}

力扣第535题:TinyURL 的加密与解密

这道题也不知道如何下手,看了下标签,使用hashmap,再看评论才知道,将shorturl存入hashmap,解码的时候就取值即可。
其中先生成的随机字符串,再进行存入hashmap中,这样的话看起来就不难了。

public class Codec {
   

    Map<String,String> map = new HashMap<>();
    static String INDEX = "0123456789qwertyuiopasdfghjklmnbvcxzQWERTYUIOPLKJHGFDSAZXCVBNM" ;
    static String PERFIX = "http://tinyurl.com/";
    int indexlen = INDEX.length();

    // Encodes a URL to a shortened URL.
    public String encode(String longUrl) {
   
        char ch[] = new char[6];
        for(int i = 0 ; i <6;i++)
        {
   
            ch[i] = INDEX.charAt((int)Math.random()*indexlen);
        }
        String shortUrl = PERFIX+new String(ch);
        if(!map.containsKey(shortUrl))
        {
   
            map.put(shortUrl,longUrl);
        }
        return shortUrl;
        
    }

    // Decodes a shortened URL to its original URL.
    public String decode(String shortUrl) {
   
        return map.get(shortUrl);
       
    }
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值