当前位置:网站首页>String inversion exercises 344, 541, 557, 151
String inversion exercises 344, 541, 557, 151
2022-04-22 14:13:00 【Borrow some hair】
151. Flip the words in the string
Given a string , Flip each word in the string one by one .
Example 1:
Input : “the sky is blue”
Output : “blue is sky the”
Example 2:
Input : " hello world! "
Output : “world! hello”
explain : The input string can contain extra spaces before or after , But the reversed characters cannot include .
Example 3:
Input : “a good example”
Output : “example good a”
explain : If there are extra spaces between two words , Reduce the space between inverted words to just one .
explain :
No space characters make up a word .
The input string can contain extra spaces before or after , But the reversed characters cannot include .
If there are extra spaces between two words , Reduce the space between inverted words to just one .
Answer key :
Double pointer , Reverse traversal , Add each word to res, Finally, it is spliced into a string
sloution:
class Solution {
public String reverseWords(String s) {
s=s.trim();
int j=s.length()-1,i=j;
StringBuilder res=new StringBuilder();
while(i>=0){
while(i >= 0 && s.charAt(i) != ' ') i--; // Search for the first space
res.append(s.substring(i + 1, j + 1) + " "); // Add words
while(i >= 0 && s.charAt(i) == ' ') i--; // Skip spaces between words
j = i; // j The last character pointing to the next word
}
return res.toString().trim(); // Convert to a string and return
}
}
541. Reverse string II
Given a string s And an integer k, You need to check every 2k Before characters k Characters to reverse .
If the remaining characters are less than k individual , Reverse all remaining characters .
If the remaining characters are less than 2k But greater than or equal to k individual , Before reversal k Characters , The rest of the characters remain the same .
Example :
Input : s = “abcdefg”, k = 2
Output : “bacdfeg”
Tips :
The string contains only lowercase letters .
The length and k stay [1, 10000] Within the scope of .
Answer key :
1) Double pointer Be careful String Objects are immutable objects , have access to toCharArray()
2k For a group , front k Elements are inverted , after k The first element remains unchanged .
sloution:
class Solution {
public String reverseStr(String s, int k) {
char[] ch = s.toCharArray();
for(int i=0;i<ch.length;i+=2*k){
int left=i;
int right=(i+k-1<ch.length)?i+k-1:ch.length-1;// Transboundary
while (left <= right){
char temp = ch[left];
ch[left] = ch[right];
ch[right] = temp;
left++;
right--;
}
}
String str = new String(ch);
return str;
}
}
344. Reverse string
Write a function , Its function is to invert the input string . Input string as character array char[] Given in the form of .
Do not allocate extra space to another array , You have to modify the input array in place 、 Use O(1) To solve this problem .
You can assume that all characters in an array are ASCII Printable characters in code table .
Example 1:
Input :[“h”,“e”,“l”,“l”,“o”]
Output :[“o”,“l”,“l”,“e”,“h”]
Example 2:
Input :[“H”,“a”,“n”,“n”,“a”,“h”]
Output :[“h”,“a”,“n”,“n”,“a”,“H”]
Answer key : Double pointer
sloution:
class Solution {
public void reverseString(char[] s) {
int left=0;
int right=s.length-1;
while(left<right){
char tmp=s[left];
s[left]=s[right];
s[right]=tmp;
left++;
right--;
}
}
}
557. Invert the words in the string III
Given a string , You need to reverse the character order of each word in the string , Keep the initial order of spaces and words .
Example :
Input :“Let’s take LeetCode contest”
Output :“s’teL ekat edoCteeL tsetnoc”
class Solution {
public String reverseWords(String s) {
String[] strs=s.split(" ");
StringBuffer buffer = new StringBuffer();
for(int i=0;i<strs.length;i++){
buffer.append(new StringBuffer(strs[i]).reverse().toString());
buffer.append(" ");
}
return buffer.toString().trim();
}
}
ToString() Is the way to convert to a string Trim() It's the way to get rid of the spaces on both sides
Java StringBuffer and StringBuilder class
When you modify a string , Need to use StringBuffer and StringBuilder class .
and String Class is different from ,StringBuffer and StringBuilder Class can be modified many times , And don't generate new unused objects .StringBuilder Class in Java 5 It was proposed that , It and StringBuffer The biggest difference between them is StringBuilder Is not thread safe ( Can't sync access ).
because StringBuilder Compare with StringBuffer Speed advantage , So in most cases, it is recommended to use StringBuilder class . However, when the application requires thread safety , Must be used StringBuffer class .
ToString() Is the way to convert to a string Trim() It's the way to get rid of the spaces on both sides
版权声明
本文为[Borrow some hair]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204221411324251.html
边栏推荐
猜你喜欢

2022 tea artist (intermediate) examination simulation 100 questions and simulation examination

Method of running uniapp to applet simulator - uniapp opens wechat developer tool preview support - hbuilderx

2D conversion (move: translate, rotate: rotate, scale: scale, 2D conversion synthesis)

CRM系统改善客户体验的方法

Ebpf learning - getting started

translucentTB汉化界面 - 菜单汉化 - 怎么使用 - win11任务栏透明效果

Huawei cloud media Zha Yong: Huawei cloud's technical practice in the field of video AI transcoding

TensorFlow-ValueError: ‘images‘ contains no shape

What does log desensitization mean? Why do you do log desensitization?

处理高并发问题思路
随机推荐
HashTable哈希表与统计594、350、|554、609、454、18
日志脱敏是什么意思?为什么要做日志脱敏?
双指针||有序数组去重 排序链表移除元素 26、27、83
CPT 104_ Lab 09
Notes sur le développement de la tarte aux framboises (XII): commencer à étudier la suite UNO - 220 de la tarte aux framboises de contrôle industriel advantech (i): Introduction et fonctionnement du s
Qt创建窗口闪退的问题
C Primer Plus --- program list 13.2 reduto c
华为云媒体査勇:华为云在视频AI转码领域的技术实践
BCC-stackcount
Timer--
CRM系统改善客户体验的方法
Brief description of three elements of LAN characteristics
Solve command line is too long Shorten command line for........ error
多线程初阶
FastDFS 安装和配置
HashTable哈希表与索引1、599、219
[finally waiting for you] wechat voice forwarding method - voice message forwarding
Crater encountered in calling bash script by makefile
uniapp转微信开发者工具报错 - [ app.json 文件内容错误] app.json: 未找到 [“sitemapLocation“] 对应的 sitemap.json 文件
BinaryTree练习 从前序与中序、中序与后序遍历序列构造二叉树||重构二叉树654、105、106