This is the 22nd day of my participation in the Genwen Challenge
The title
Enter a string and print out all permutations of the characters in the string.
You can return this array of strings in any order, but no repeating elements.
Example:
Input: s = “ABC” output: [” ABC “, “acb”, “America”, “bca”, “cab”, “cba”]
Limitations:
1 <= length of s <= 8
Their thinking
-
To convert a string into a character array, each time in the character array, select a character to fill in a specific position, and record the characters that have been used, when all the characters are used up after the character sequence is one of the permutations
-
Since 1 <= s has a length <= 8, you can directly use byte to record the selected characters
code
class Solution {
Set<String> res=new HashSet<>();
public String[] permutation(String s) {
char[] chars = s.toCharArray();
bcP(chars,0, (byte) 0.new StringBuilder());
String[] ress = new String[res.size()];
Iterator<String> iterator = res.iterator();
for (int i = 0; i < res.size(); i++) {
ress[i]=iterator.next();
}
return ress;
}
public void bcP(char[] chars,int cur,byte check,StringBuilder stringBuilder)
{
if(cur==chars.length){
res.add(stringBuilder.toString());
}
for (int i=0,th=1<<(chars.length-1); i<chars.length; i++,th>>=1)
{
if((th&check)! =0)
continue;
check^=th;
stringBuilder.append(chars[i]);
bcP(chars,cur+1,check,stringBuilder);
stringBuilder.deleteCharAt(stringBuilder.length()-1); check^=th; }}}Copy the code
Topic 2
You are given the string num, which represents a large integer. Find the odd number with the greatest value among all non-empty substrings of num and return it as a string. If no odd number exists, an empty string “” is returned.
A substring is a contiguous sequence of characters in a string.
Example 1:
Input: num = “52” Output: “5” Description: Only “5”, “2”, and “52” are non-empty substrings. 5″ is the only odd number. Example 2:
Input: num = “4206” Output: “” Explanation: There is no odd number in “4206”. Example 3:
Input: num = “35427” Output: “35427” Description: “35427” is itself an odd number.
Tip:
- 1 <= num.length <= 105
- Num consists only of numbers and does not contain leading zeros
Their thinking
You only need to search from the lowest digit to the highest digit to find the least significant odd character, then from this position to the highest digit, it is the largest odd number
code
class Solution {
public String largestOddNumber(String num) {
for (int i=num.length()-1; i>=0; i--) {if((num.charAt(i)-'0') %2= =1)
return num.substring(0,i+1);
}
return ""; }}Copy the code