文章目录
力扣第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