[java实现]常见算法之字符串操作
一、字符串反转
把一个句子中的打次进行反转,比如“how are you” ,变为 “you are how”
// 字符串反转
public class StringTest { // 字符反转的方法
private void swap(char[] c, int front, int end) { if (front > end || end >= c.length) {
return;
} while (front < end) { char tmp = c[front];
c[front] = c[end];
c[end] = tmp; front++;
end--;
}
} // O(n)
public String swapStr(String str) { char[] cArr = str.toCharArray(); // 整个字符串的字符反转
swap(cArr, 0, cArr.length - 1); // 反转整个字符串中的所有字母,how are you -> uoy era woh int begin = 0; // 对字符串中的每个单词反转,除了最后一单词
for (int i = 0; i < cArr.length; i++) { if (cArr[i] == ' ') {
swap(cArr, begin, i - 1);
begin = i + 1;
}
} // 最后一个单词的反转
swap(cArr, begin, cArr.length - 1); return new String(cArr);
} public static void main(String[] args) { String str = "how are you";
System.out.println(new StringTest().swapStr(str));
} }
二、判断字符串是否由相同的字符组成
判断连个字符串的字母个字母的个数是否一样,顺序可以不同, 如“aaaabc” 和“cbaaaa”是相同的
// 判断字符串是否由相同的字符组成
public class StringTest { // 方法一 可以死任意字符 O(nlogn)
public boolean compareStr(String str1, String str2) { byte[] bs1 = str1.getBytes();
byte[] bs2 = str2.getBytes(); Arrays.sort(bs1);
Arrays.sort(bs2); str1 = new String(bs1);
str2 = new String(bs2); if (str1.equals(str2)) {
return true;
} else {
return false;
}
} // 只能是ASCII码 方法二 O(n)
public boolean compareStr2(String str1, String str2) { byte[] bs1 = str1.getBytes();
byte[] bs2 = str2.getBytes(); int bCount[] = new int[256]; for (int i = 0; i < bs1.length; i++)
bCount[bs1[i] ]++;
for (int i = 0; i < bs2.length; i++)
bCount[bs2[i] ]--;
for (int i = 0; i < 256; i++) { if (bCount[i] != 0) {
return false;
} }
return true; } public static void main(String[] args) { String str1 = "aaaabbc";
String str2 = "cbaaaab"; System.out.println(new StringTest().compareStr2(str1, str2)); } }
三、字符串中单词的统计
给定一段空格分开的字符串,判断单词的个数
// 字符串中单词的统计
public class StringTest { // O(n)
public int wordCount(String str) { int word = 0;
int count = 0;
for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == ' ')
word = 0;
else if (word == 0 ) {
word = 1;
count++;
}
} return count;
} public static void main(String[] args) { String str = "i am a good boy"; System.out.println(new StringTest().wordCount(str)); } }
四、删除字符串中重复的字符
删除字符串中国重复的字符。如good -> god
// 删除字符串中重复的字符
public class StringTest { // O(n^2)
public String removeDuplicate(String str) { char[] cs = str.toCharArray();
int n = cs.length; for (int i = 0; i < n; i++) { if (cs[i] == '\0')
continue; for (int j = i + 1; j < n; j++) { if (cs[j] == '\0')
continue;
if (cs[i] == cs[j])
cs[j] = '\0';
}
} int be = 0;
for (int i = 0; i < n; i++) {
if (cs[i] != '\0')
cs[be++] =cs[i];
} return new String(cs, 0, be);
} // 方法二: O(n)
public String removeDuplicate2(String str) { char[] cs = str.toCharArray();
int n = cs.length; int count[] = new int[256];
for (int i = 0; i < cs.length; i++) {
if (count[cs[i]] != 0)
cs[i] = '\0';
count[cs[i]]++;
} int be = 0;
for (int i = 0; i < n; i++) {
if (cs[i] != '\0')
cs[be++] = cs[i];
} return new String(cs, 0, be);
} public static void main(String[] args) { String str = "aaaabbc"; System.out.println(new StringTest().removeDuplicate(str)); } }
五、按要求打印给定数组的排列情况
如1,2,2,3,4,5,要求第四位不为4,3和5不能相连
// 按要求打印数组的排列情况
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set; public class StringTest { boolean visited[];
String combination = "";
int graph[][] = null; public void getAllCombination(int arr[]) { int n = arr.length;
graph = new int[n][n];
visited = new boolean[n]; buildGraph(arr, graph); Set<String> set = new HashSet<>(); for (int i = 0; i < n; i++) {
depthFirstSearch(i, set, arr);
} Iterator<String> iterator = set.iterator(); while (iterator.hasNext()) {
String string = (String) iterator.next();
System.out.println(string);
}
} /**
* 按照深度优先遍历 图,将符合要求的组合加入到set中,自动去重
*
* @param start
* @param set
* @param arr
*/
private void depthFirstSearch(int start, Set<String> set, int arr[]) {
visited[start] = true;
combination += arr[start]; if (combination.length() == arr.length) {
if (combination.indexOf("4") != 2) {
set.add(combination);
}
} for (int j = 0; j < arr.length; j++) {
if (graph[start][j] == 1 && visited[j] == false)
depthFirstSearch(j, set, arr);
} // 什么意思?
combination = combination.substring(0, combination.length() - 1);
visited[start] = false;
} /**
* 根据传入的数构建一个图,图中的 3,5 不能相连
*
* @param arr
* @param graph
* @return
*/
private int[][] buildGraph(int arr[], int[][] graph) { for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
if (arr[i] == arr[j])
graph[i][j] = 0;
else
graph[i][j] = 1;
}
} graph[3][5] = 0;
graph[5][3] = 0; return graph;
} public static void main(String[] args) { int arr[] = { 1, 2, 2, 3, 4, 5 };
new StringTest().getAllCombination(arr); } }
六、输出字符串的所有组合
给定一个字符串,输出该字符串中字符的所有组合
// 输出字符串的所有组合
public class StringTest {
public void combineRecursive(char[] c, int begin, int len, StringBuffer sb) {
if (len == 0) {
System.out.print(sb + " ");
return;
}
if (begin == c.length)
return;
sb.append(c[begin]);
combineRecursive(c, begin + 1, len - 1, sb);
sb.deleteCharAt(sb.length() - 1);
combineRecursive(c, begin + 1, len, sb);
}
public static void main(String[] args) {
String s = "abc";
char[] cs = s.toCharArray();
StringBuffer sb = new StringBuffer();
for (int j = 1; j < cs.length; j++) {
new StringTest().combineRecursive(cs, 0, j, sb);
}
}
}
[java实现]常见算法之字符串操作的更多相关文章
- Java 蓝桥杯 算法训练 字符串的展开 (JAVA语言实现)
** 算法训练 字符串的展开 ** 题目: 在初赛普及组的"阅读程序写结果"的问题中,我们曾给出一个字符串展开的例子:如果在输入的字符串中,含有类似于"d-h" ...
- Java数据结构和算法总结-字符串及高频面试题算法
前言:周末闲来无事,在七月在线上看了看字符串相关算法的讲解视频,收货颇丰,跟着视频讲解简单做了一下笔记,方便以后翻阅复习同时也很乐意分享给大家.什么字符串在算法中有多重要之类的大路边上的客套话就不多说 ...
- Java数据结构和算法总结-字符串相关高频面试题算法
前言:周末闲来无事,看了看字符串相关算法的讲解视频,收货颇丰,跟着视频讲解简单做了一下笔记,方便以后翻阅复习同时也很乐意分享给大家.什么字符串在算法中有多重要之类的大路边上的客套话就不多说了,直接上笔 ...
- Java面试常见算法题
1.实现字符串反转 提供七种方案实现字符串反转 import java.util.Stack; public class StringReverse { public static String re ...
- Java字符串操作及与C#字符串操作的不同
每种语言都会有字符串的操作,因为字符串是我们平常开发使用频率最高的一种类型.今天我们来聊一下Java的字符串操作及在某些具体方法中与C#的不同,对于需要熟悉多种语言的人来说,作为一种参考.进行诫勉 首 ...
- Java中的字符串操作(比较String,StringBuiler和StringBuffer)
一.前言 刚开始学习Java时,作为只会C语言的小白,就为其中的字符串操作而感到震撼.相比之下,C语言在字节数组中保存一个结尾的\0去表示字符串,想实现字符串拼接,还需要调用strcpy库函数或者自己 ...
- 常见算法合集[java源码+持续更新中...]
一.引子 本文搜集从各种资源上搜集高频面试算法,慢慢填充...每个算法都亲测可运行,原理有注释.Talk is cheap,show me the code! 走你~ 二.常见算法 2.1 判断单向链 ...
- java入门学习笔记之2(Java中的字符串操作)
因为对Python很熟悉,看着Java的各种字符串操作就不自觉的代入Python的实现方法上,于是就将Java实现方式与Python实现方式都写下来了. 先说一下总结,Java的字符串类String本 ...
- JAVA基础--JAVA API常见对象(字符串&缓冲区)11
一. String 类型 1. String类引入 第二天学习过Java中的常量: 常量的分类: 数值型常量:整数,小数(浮点数) 字符型常量:使用单引号引用的数据 字符串常量:使用双引号引用 ...
随机推荐
- jQuery validator 增加多个模板
今天学了jquery validator 可以增加多个模板,而不用写长长的js代码.废话少说,直接上例子 这段是要添加的模板 上面是把模板部分是要重复增加多个的部分,需独立出来,用textarea标签 ...
- Castle ActiveRecord学习(七)使用日志
暂无 参考:http://terrylee.cnblogs.com/archive/2006/04/14/374829.html
- Please ensure that adb is correctly located at 。。。。。。。。。。。。
遇到问题描述: 运行Android程序控制台输出 [2012-07-18 16:18:26 - ] The connection to adb is down, and a severe error ...
- 不要怂,就是GAN (生成式对抗网络) (一): GAN 简介
前面我们用 TensorFlow 写了简单的 cifar10 分类的代码,得到还不错的结果,下面我们来研究一下生成式对抗网络 GAN,并且用 TensorFlow 代码实现. 自从 Ian Goodf ...
- mongo学习- mapReduce操作事例
源数据: { "_id" : 1.0, "name" : "abc", "age" : 43.0, "type ...
- java grpc简单例子
原文地址:http://blog.csdn.net/jek123456/article/details/53465033 用eclipse新建一个maven项目,Id信息如下 <groupId& ...
- 用U盘安装Ubuntu主系统
用U盘安装Ubuntu主系统 0. 学习Ubuntu系统的的动机 ubuntu系统的内核是linux系统,通过Ubuntu的学习,掌握lInux服务器搭建!!!! 硬件要求:闲置的笔记本 + U盘 ...
- Python学习-8.Python的循环语句-while语句
例子: i = 1 while i < 10: print(i) i+=1 else: print('finish') 输出1至9和finish 在while语句中同样支持for语句所支持的co ...
- 【转】ProGuard的作用、使用及bug分析
原文地址:http://blog.csdn.net/forlong401/article/details/23539123. http://www.trinea.cn/android/proguard ...
- maven多模块启动required a bean of type com.xxx.xxx.service that could not be found.
Description: Field testService in com.xxx.xxx.api.controller.TestController required a bean of type ...