20200814: Likou 201 Weekly Competition Problem Solving Record

Likou 201 Weekly Competition Problem Solution Record

topic

  1. Organize strings

Insert picture description here
Insert picture description here

  1. Find the Kth bit in the Nth binary string
    Insert picture description here

Ideas and algorithms

  1. In the first question, things like Xiao Xiaole are implemented directly with the stack, pay attention to the details of the code
  2. The second question is also a question that can be simulated directly according to the meaning of the question, and the invert function he mentioned can be realized.
  3. To record, today I will add more professional knowledge that I lacked before the beginning of school, involving signal systems, communication principles, and digital signal processing. Keep the details

Code

  1. Organize strings
class Solution {
    
    
    public String makeGood(String s) {
    
    
    
        Stack<Character> stack = new Stack<Character>();
        char[] ch = s.toCharArray();
        for (int i = 0; i < ch.length; i++) {
    
    
            
            if (stack.isEmpty()) {
    
    
                stack.push(ch[i]);
                continue;
            } 
            char tmp = stack.peek();
            if (tmp - ch[i] == 32 || tmp - ch[i] == -32) {
    
    
                stack.pop();
            } else {
    
    
                stack.push(ch[i]);
            }
            
        }

        StringBuilder sb = new StringBuilder();
        for (Character s1 : stack) {
    
    
            sb.append(s1);
        }

        return sb.toString();
    }
}
  1. Find the Kth bit in the Nth binary string
package com.immunize.leetcode.findKthBit;

public class Solution {
    
    
	public char findKthBit(int n, int k) {
    
    
		// 产生这个Sn
		String s = generateString(n);
		// 返回Sn的第k个值返回即可
		return s.charAt(k - 1);
	}

	private String generateString(int n) {
    
    
		String[] sn = new String[n];
		sn[0] = "0";
		for (int i = 1; i < n; i++) {
    
    
			sn[i] = sn[i - 1] + "1" + reverse(invert(sn[i - 1]));
		}
		return sn[n - 1];
	}

	private String reverse(String invert) {
    
    
		StringBuilder sb = new StringBuilder();
		return sb.append(invert).toString();
	}

	private String invert(String sn) {
    
    
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < sn.length(); i++) {
    
    
			if (sn.charAt(i) == '1') {
    
    
				sb.append('0');
			} else {
    
    
				sb.append('1');
			}
		}
		return sb.toString();
	}
}

Write at the end

The purpose of updating the blog is to record your own learning situation, so that you can learn from time to time and avoid putting the cart before the horse.

Guess you like

Origin blog.csdn.net/qq_36828395/article/details/108016117