京东笔试编程题,重叠子串和括弧


京东笔试,第一条关于重叠子串的题目 


public static void main(String[] args) {

Scanner in = new Scanner(System.in);

String s = in.next();

char[] str = s.toCharArray();

int index = -1;

for (int i = 1; i < str.length; i++) {

boolean overlap = true;

for (int j = 0; i+j < str.length; j++) {

if (str[i+j] != str[j]) {

overlap = false;

break;

}

}

if (overlap) {

index = i;

break;

}

}

String res = null;

if (index != -1) {

res = s + s.substring(str.length - index);

}

else {

res = s + s;

}

System.out.println(res);

}



第二道 关于括弧的题目



public class Second {

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

String line = in.nextLine();

HashMap<String, Integer> map = new HashMap<>();

int time = findTime(line, map);

System.out.println(time);

}

public static int findTime(String line, HashMap<String, Integer> map) {

if (line.isEmpty()) {

return 1;

}

if (map.containsKey(line)) {

return map.get(line);

}

int res = 0;

for (int i = 1; i < line.length(); i++) {

if (line.charAt(i) == ')') {

String left = null;

if (i == 1) {

left = line.substring(2);

}

else {

left = line.substring(1, i) + line.substring(i+1);

}

if (isLegal(left)) {

res += findTime(left, map);

}

}

}

map.put(line, res);

return res;

}

public static boolean isLegal(String str) {

int l = 0, r = 0;

for (int i = 0; i < str.length(); i++) {

if (str.charAt(i) == '(') {

l++;

}

else {

r++;

}

if (r > l) {

return false;

}

}

return true;

}

}



#京东#
全部评论

相关推荐

牛客154160166号:9月底还给我发短信,好奇怪,我24届的
点赞 评论 收藏
分享
有工作后先养猫:太好了,是超时空战警,我们有救了😋
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务