当前位置:网站首页>Day 4 of leetcode question brushing
Day 4 of leetcode question brushing
2022-07-16 07:50:00 【The sun is falling】
1. A string that concatenates all words
Given a string s And some of the Same length 's words words . find s It happens that words The starting position of the substring formed by concatenation of all words in . Pay attention to the relationship between the string and words The words in match exactly , No other characters in the middle , But there's no need to think about words The order in which words are concatenated . Example 1: Input :s = "barfoothefoobarman", words = ["foo","bar"] Output :[0,9] explain : From the index 0 and 9 The first substrings are "barfoo" and "foobar" . The order of output is not important , [9,0] It's also a valid answer . Example 2: Input :s = "wordgoodgoodgoodbestword", words = ["word","good","best","word"] Output :[] Example 3: Input :s = "barfoofoobarthefoobarman", words = ["bar","foo","the"] Output :[6,9,12]
analysis :
Using the slide window . Because the word length is fixed , So we can calculate whether the number of words intercepted from the string is equal to words Li equivalency , So we can borrow hash table . One is hash table words, A hash table is a truncated string , Compare whether two hashes are equal .
public static List<Integer> solution2(String s, String[] words) {
List<Integer> res = new ArrayList<>();
Map<String, Integer> wordsMap = new HashMap<>();
if (s.length() == 0 || words.length == 0) return res;
for (String word: words) {
// Main string s There is no such word in English , Direct return null
if (s.indexOf(word) < 0) return res;
// map Save each word in , And the number of times it appears
wordsMap.put(word, wordsMap.getOrDefault(word, 0) + 1);
}
// The length of each word , Total length
int oneLen = words[0].length(), wordsLen = oneLen * words.length;
// Main string s The length is less than the sum of words , Returns an empty
if (wordsLen > s.length()) return res;
// Only discuss from 0,1,..., oneLen-1 The starting substring ,
// The window size for each match is wordsLen, Move back one word at a time , The current window position is maintained by the left and right windows
for (int i = 0; i < oneLen; ++i) {
// Left and right windows
int left = i, right = i, count = 0;
// Count each qualified word
Map<String, Integer> subMap = new HashMap<>();
// The right window cannot exceed the length of the main string
while (right + oneLen <= s.length()) {
// Get a word
String word = s.substring(right, right + oneLen);
// There is a window moving right
right += oneLen;
// words[] There is no such word in English , Then the current window must fail to match , Move directly to the right after this word
if (!wordsMap.containsKey(word)) {
left = right;
// Word statistics in the window map Empty , Re count
subMap.clear();
// Count the words that meet the requirements 0
count = 0;
} else {
// Count the number of occurrences of this word in the current substring
subMap.put(word, subMap.getOrDefault(word, 0) + 1);
++count;
// If this word appears more than words[] The number of times it corresponds to , And because of every match and words Substrings of equal length
// Such as ["foo","bar","foo","the"] "| foobarfoobar| foothe"
// the second bar Although it is words[] The words in , But the number is copied , Then shift the length of one word to the right "|barfoobarfoo|the"
// bar Still not in line with , So directly from this inconformity bar Then start matching , That is to say, the non-conforming bar And the words before it ( strand ) Move it all out
while (subMap.getOrDefault(word, 0) > wordsMap.getOrDefault(word, 0)) {
// Count characters from the current window map Delete all words from the left window to the number limit ( Times minus one )
String w = s.substring(left, left + oneLen);
subMap.put(w, subMap.getOrDefault(w, 0) - 1);
// Subtract one from the number of words that match
--count;
// Move the left window position to the right
left += oneLen;
}
// The current window string meets the requirements
if (count == words.length) res.add(left);
}
}
}
return res;
}2. Binary 1 The number of
Write a function , Input is an unsigned integer ( In the form of a binary string ), Returns the number of digits in its binary expression as '1' The number of ).
Input :n = 11 ( Console input 00000000000000000000000000001011)
Output :3
explain : Binary string of input 00000000000000000000000000001011 in , There are three of them '1'.
Input :n = 128 ( Console input 00000000000000000000000010000000)
Output :1
explain : Binary string of input 00000000000000000000000010000000 in , There is one in all for '1'.
analysis :
And operation &: There is a binary number n, if n&1 = 0 , be n The rightmost bit of binary is 0; if n&1 = 1, Then the rightmost bit of binary is 1.
Algorithm flow :
Initialize the quantity statistics variable res = 0.
Loop bit by bit : When n = 0 Jump out when .
res += n & 1 : if n \& 1 = 1, Then statistics res Add one .
n >>= 1 : Put the binary number n Move one unsigned right ( Java Right shift without sign in to ">>>>>>" ) .
Return statistics quantity res .
public class Solution {
public int hammingWeight(int n) {
int res = 0;
while(n != 0) {
res += n & 1;
n >>>= 1;
}
return res;
}
}
3. Integer power of value
Realization pow(x,n), Computation x Of n Power function . Do not use library functions , At the same time, there is no need to consider the problem of large numbers .
analysis :
class Solution {
public double myPow(double x, int n) {
return n>0?mult(x,n):1/mult(x,-n);
}
public double mult(double x, int n){
if(n==0)
return 1.0;
double y = mult(x, n/2);
return n%2==0?y*y:y*y*x;
}
}4. Input number n, Print out from... In order 1 To the biggest n A decimal number . Such as input 3, Then print out 1、2、3 Up to the biggest 3 digit 999.
There's nothing to analyze
class Solution {
public int[] printNumbers(int n) {
int maxnum = (int) Math.pow(10, n)-1;
int[] res = new int[maxnum];
for (int i = 0; i < maxnum; i++) {
res[i] = i+1;
}
return res;
}
}5. Delete the node of the linked list
Given the head pointer of one-way linked list and the value of a node to be deleted , Define a function to delete the node .
Return the head node of the deleted linked list .
analysis :
Double pointer .
class Solution {
public ListNode deleteNode(ListNode head, int val) {
if (head.val == val){
head = head.next;
return head;
} else {
ListNode prenode = head;
ListNode node = head.next;
while(node!=null){
if(node.val==val){
prenode.next = node.next;
break;
}else {
prenode = node;
node = node.next;
}
}
}
return head;
}
}边栏推荐
- The core difference between fairness and unfairness of reentrantlock
- Wechat native payment
- Linux上安装Redis
- POI framework learning - Import and export cases
- 传输层协议
- Automatically back up mysql. And keep the case for 7 days
- 0 1背包 填表实现
- How to write test cases for initial testing? Take you to write a qualified test case from three aspects
- Five years' experience: the monthly salary is 3000 to 30000, and the change of Test Engineers
- Detailed explanation of sliding window
猜你喜欢

还在用策略模式解决 if-else?Map+函数式接口方法才是YYDS

File management - Alibaba cloud OSS learning (I)

Dictionary tree

爬虫——有道翻译

Is it reliable to switch to software testing at the age of 30? The mental journey of a person who came here is for you who are confused

传输层协议

RAID disk array

A simple JVM tuning. Write it in your resume

2021-11-7 bugku question making record 25 - Post

(一)输入输出
随机推荐
Redis只能做缓存?太out了!
还在用策略模式解决 if-else?Map+函数式接口方法才是YYDS
5年经验之谈:月薪3000到30000,测试工程师的变“行”记...
Wechat native payment
一次简单的 JVM 调优,拿去写到简历里
关于pycharm汉化 2020-09-20
Still using enumeration in MySQL? Pay attention to these traps!
还在使用 MySQL 中使用枚举?这些陷阱一定要注意!
A man with an annual salary of 35W was dismissed from the test, and his words were thought-provoking
Redis master-slave cluster construction and sentinel mode configuration
"Why do you want to resign, Tencent, which broke its head?"
IDEA 注释模板,这样配置才够逼格!
appium中控件坐标及控件属性获取
Desired in appium_ Caps parameter record
26 years old, has worked in automation for three years, and the monthly salary is only 12K. Can you change jobs and find a higher salary job?
Dictionary tree
CCF 201909-1 称检测点查询
jmeter中设置登录接口只调用一次
How to self-study software testing? [super comprehensive analysis from 0 to 1] (with learning notes)
(一)输入输出