目录
倒置字符串(字符串)
题目解析
1.题目链接:倒置字符串_牛客题霸_牛客网
2.题目描述
描述
将一句话的单词进行倒置,标点不倒置。比如 I like beijing. 经过函数后变为:beijing. like I
输入描述:
每个测试输入包含1个测试用例: I like beijing. 输入用例长度不超过100
输出描述:
依次输出倒置之后的字符串,以空格分割
示例1
输入:
I like beijing.
输出:
beijing. like I
讲解算法原理
解法:
算法思路:
找到规律反转字符串即可。
编写代码
c++算法代码:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string s;
getline(cin, s);
reverse(s.begin(), s.end());
int left = 0, n = s.size(); while(left < n)
{
int right = left;
while(right < n && s[right] != ' ') // 找单词 {
right++;
}
reverse(s.begin() + left, s.begin() + right); while(right < n && s[right] == ' ') right++; left = right;
}
cout << s << endl;
return 0;
}
java算法代码:
import java.util.Scanner;import java.io.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main
{
public static void Reverse(char[] s, int left, int right)
{
int l = left, r = right; while(l < r)
{
char ch = s[l]; s[l] = s[r]; s[r] = ch; l++; r--;
}
}
public static void main(String[] args) throws Throwable
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
char[] s = br.readLine().toCharArray(); int n = s.length;
Reverse(s, 0, n - 1);
int left = 0;
while(left < n)
{
int right = left;
while(right < n && s[right] != ' ') right++; // 找单词 Reverse(s, left, right - 1);
while(right < n && s[right] == ' ') right++; // 跳过空格 left = right; }
for(char ch : s) System.out.print(ch);
}
}
删除公共字符(哈希)
题目解析
1.题目链接:删除公共字符_牛客题霸_牛客网
2.题目描述
描述
输入两个字符串,从第一字符串中删除第二个字符串中所有的字符。例如,输入”They are students.”和”aeiou”,则删除之后的第一个字符串变成”Thy r stdnts.”
输入描述:
每个测试输入包含2个字符串
输出描述:
输出删除后的字符串
示例1
输入:
They are students.
aeiou输出:
Thy r stdnts.
讲解算法原理
解法:
算法思路:
⽤哈希表记录⼀下字符串的字符信息即可。
编写代码
c++算法代码:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s, t;
getline(cin, s); getline(cin, t);
bool hash[300] = { 0 }; for(char ch : t) hash[ch] = true;
string ret;
for(auto ch : s)
{
if(!hash[ch])
{
ret += ch;
}
}
cout << ret << endl;
return 0;
}
java算法代码:
import java.util.Scanner;import java.io.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String s = br.readLine(); String t = br.readLine();
boolean[] hash = new boolean[300];
for(int i = 0; i < t.length(); i++)
{
hash[t.charAt(i)] = true;
}
for(int i = 0; i < s.length(); i++)
{
if(!hash[s.charAt(i)])
{
System.out.print(s.charAt(i));
}
}
}
}