对字符串操纵的各类笔试题
添加时间:2013-8-12 点击量:
下面列出一些在笔试中常呈现的对字符串操纵的题目,都是本人本身写的,若是哪里不合错误或者有更好的实现迎接大师指出!若是有其他题目也迎接大师贴出来!感谢!
一、实现字符串的反转,如输入abc,返回cba
1 package com.others;
2
3 public class 字符串反转 {
4
5 public static void main(String[] args) {
6 System.out.println(inverse(liuling));
7 }
8
9 public static String inverse(String str){
10 char[] chars = str.toCharArray(); //获得字符数组
11 for (int i = 0; i < chars.length/2; i++) {
12 char temp = chars[i];
13 chars[i] = chars[chars.length-i-1];
14 chars[chars.length-i-1] = temp;
15 }
16
17 return String.copyValueOf(chars);
18 }
19
20 }
二、找字符串中最长对称串
1 package com.others;
2
3
4 public class 找字符串中最长对称串 {
5
6 public static void main(String[] args) {
7 System.out.println(findSymmetry(dgaabcddcbadfabcdefghijkkjihgfedcbagaaabbccddddccbbaaaf));
8 }
9 /
10 找最长对称字符串,应当重最大长度开端找,找到就返回
11 若是从最小开端找的话,效力好低,那找到一个还要持续找,直到找到最长的为止
12 若是找对称的个数的话那就另当别论了,必须得所有都断定
13 /
14 public static String findSymmetry(String str){
15 String symmetryStr;
16 for (int i = str.length()-1; i > 0; i--) { //找是否有长度为i的对称串,i从最大开端
17 for (int j = 0; j<str.length() && j+i<str.length(); j++) {
18 symmetryStr = str.substring(j, j+i+1);
19 char[] chars = symmetryStr.toCharArray();
20 int k;
21 //断定是否为对称串
22 for (k = 0; k < chars.length/2; k++) {
23 if(chars[k] != chars[chars.length-k-1]){
24 break;
25 }
26 }
27 //若是对称则返回
28 if(k == chars.length/2){
29 return symmetryStr;
30 }
31 }
32 }
33 return ;
34 }
35 }
三、求字符串中对称串的个数
1 package com.others;
2
3 public class 求字符串中对称串的个数 {
4
5
6 public static void main(String[] args) {
7 System.out.println(findSymmetryCount(aabbaaffddphpaffa));
8 }
9 public static int findSymmetryCount(String str){
10 int count = 0;
11 String symmetryStr;
12 for (int i = 1; i < str.length(); i++) {
13 for (int j = 0; j<str.length() && j+i<str.length(); j++) {
14 symmetryStr = str.substring(j, j+i+1);
15 char[] chars = symmetryStr.toCharArray();
16 int k;
17 //断定是否为对称串
18 for (k = 0; k < chars.length/2; k++) {
19 if(chars[k] != chars[chars.length-k-1]){
20 break;
21 }
22 }
23 //若是对称则count+1
24 if(k == chars.length/2){
25 count++;
26 }
27 }
28 }
29 return count;
30 }
31 }
四、求字符串中呈现频率高的字符
1 package com.others;
2
3 import java.util.HashMap;
4 import java.util.Map;
5
6 public class 求字符串中呈现频率高的字符 {
7
8 public static void main(String[] args) {
9 System.out.println(findHighRateChar(abcdfeeafdaf));
10 }
11 public static char findHighRateChar(String str){
12 int max = 0;
13 char c = ;
14 Map<Character, Integer> map = new HashMap<Character, Integer>();
15 char[] chars = str.toCharArray();
16 for (int i = 0; i < chars.length; i++) {
17 if(map.containsKey(chars[i])){
18 map.put(chars[i], map.get(chars[i])+1);
19 if(map.get(chars[i])>max){
20 max = map.get(chars[i]);
21 c = chars[i];
22 }
23 }else{
24 map.put(chars[i], 1);
25 }
26 }
27 return c;
28 }
29 }
有待补充......